package com.bodacn.keypoint;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;
import org.w3c.dom.Text;
import org.xmlpull.v1.XmlPullParserException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import static android.os.Environment.getDataDirectory;
import static android.os.Environment.getExternalStorageDirectory;

public class ProcsliptActivity extends Activity implements View.OnClickListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
    //全局变量
    String SaveFilePath="",SaveDBFolder="/DB";
    public static final String DB_Name ="bdmes.db";
    SQLiteDatabase mainDB;
    //全局变量
    String STORE_NAME = "Settings";
    String selectStyleID="";
    String selectOrderNo ="";
    String selectStyleNo="";
    String selectStyleSort="";
    //全局提示;
    Toast curToast;
    //顶部元素
    TextView txt_titleInv;
    Button btn_LoginUser, btn_LoginClose;
    //布局元素;
    Button btn_departRefresh, Btn_ProcRefresh,btn_AddEmpProc,btn_ClrEmpProc,btn_ReArrangeProc,btn_CopyArrangeProc,btn_SaveProcScheme,btn_ViewProcScheme,btn_proc_switchPlace,btn_proc_autoPlace;
    TextView text_SelPlaceNo,text_SelEmpName;
    TextView text_titleFactory, text_titleDepart,text_titleEmpNum;
    EditText edit_orderNo,edit_styleNo,edit_workDate;
    TextView text_titleOrderNo,text_titleStyleNo,text_titleNumber,text_titleSAMValue,text_titleTargetNum,text_titleTT;
    TextView text_ProcEmpCount,text_ProcBudgetOut,text_ProcBalanceRatio;
    ListView empListView,procListView;
    GridView arrMachineGrid,empProcGrid,machineTotalGrid;
    SideBar empSidrBar;
    TextView empDialog;
    SortAdapter empListAdapter;
    /**汉字转换成拼音的类**/
    private CharacterParser characterParser;
    private List<SortModel> SourceEmpList;
    /**根据拼音来排列ListView里面的数据类*/
    private PinyinComparator pinyinComparator;
    ImageView image_StylePic;
    //全局变量
    String curLoginUserNo,curLoginUser,curFactory, curDepartNo="",curDepart="",serviceUrl="";//操作员所属部门等信息;
    String curProduceMasterID,CPUID;
    int curPlaceCount;
    String readyOrderNo,readyStyleNo;
    private ListView procOrderListGrid;
    int curOperateTime =600;//工作分钟
    String curSAMValue="0";
    private ProgressDialog waitDialog = null;
    //组别;
    private String curOrderNo ="", curStyleNo ="",curStyleSort="",curStyleID="",curWorkDate="",selEmpID="",selEmpNo="",selEmpName="", CurPhotoFileName ="",selPlaceNo="",language="";
    //TT,默认值为60;
    private int curWorkTT =60;
    private boolean NeedReLoad=false;
    //用于存储WebService返回的结果;
    private JSONArray OrderJSONArray,TotalMachine;
    //用于存放员工表、工序表;
    private JSONArray empList,procList, empProcList,arrMachineList;

    //核心设置的代码
    protected void switchLanguage() {
        //读取配置文件-设置语言
        SharedPreferences settings = getSharedPreferences(STORE_NAME, MODE_PRIVATE);
        language=settings.getString("language",language);
        //获取资源
        Resources resources = getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        switch (language) {
            case "zh":
                config.locale = new Locale("zh","");
                resources.updateConfiguration(config, dm);
                break;
            case "en":
                config.locale = new Locale("en","");
                resources.updateConfiguration(config, dm);
                break;
            case "km":
                config.locale = new Locale("km","");
                resources.updateConfiguration(config, dm);
                break;
            default:
                config.locale = new Locale("zh","");
                resources.updateConfiguration(config, dm);
                break;
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //切换语言;
        switchLanguage();
        //启动Activity
        setContentView(R.layout.activity_procslipt);
        hideBottomUIMenu();
        //全屏;
        try{
            //取存储路径;
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                //SD卡准备好的话，优先存储;
                SaveFilePath = getExternalStorageDirectory().toString();
                Log.d("msg","用存储卡:"+SaveFilePath);
            }
            else{
                //系统内部Flash;
                SaveFilePath =this.getFilesDir().toString();
                Log.d("msg","用系统目录:"+SaveFilePath);
            }
            //组织并判断是否需要创建Root目录;
            SaveFilePath = SaveFilePath +"/BDMES";
            Log.d("msg","存储目录为:"+SaveFilePath);
            //判断是否需要创建BDMES根目录;
            if (isExternalStorageWritable()==true) {
                //主目录;
                File file = new File(SaveFilePath);
                if (!file.isDirectory()) file.mkdir();
                Log.d("msg","目录创建成功:"+ SaveFilePath );
                //数据库目录
                file = new File(SaveFilePath +SaveDBFolder);
                if (!file.isDirectory()) file.mkdir();
                Log.d("msg","目录创建成功:"+ SaveFilePath +SaveDBFolder);
            }
        } catch (Exception e){
            Toast.makeText(this,String.valueOf("出错了，"+e.getMessage()),Toast.LENGTH_LONG).show();
        }
        //创建对话框，
        waitDialog=new ProgressDialog(this);
        waitDialog.setTitle("请稍等");
        waitDialog.setIndeterminate(true);
        //初始提醒;
        curToast = Toast.makeText(this, "", Toast.LENGTH_LONG);
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curFactory=paramBundle.getString("curFactory");
        curDepartNo=paramBundle.getString("curDepartNo");
        curDepart=paramBundle.getString("curDepart");
        curProduceMasterID=paramBundle.getString("curProduceMasterID");
        curStyleID=paramBundle.getString("curStyleID");
        curOrderNo=paramBundle.getString("curOrderNo");
        curStyleNo=paramBundle.getString("curStyleNo");
        curStyleSort=paramBundle.getString("curStyleSort");
        curPlaceCount=paramBundle.getInt("PlaceCount");
        curOperateTime=paramBundle.getInt("OperateTime");
        serviceUrl=paramBundle.getString("serviceUrl");
        CPUID=paramBundle.getString("CPUID");
        System.out.println(paramBundle);
        //初始化按键，并将页面加载到fragment列表中;
        InitView();
        //置车间及部门;
        text_titleFactory.setText(curFactory);
        text_titleDepart.setText(curDepart);
        btn_LoginUser.setText(curLoginUser);
        //打开或创建数据库文件;
        mainDB = openOrCreateDatabase(DB_Name, this.MODE_PRIVATE, null);
        //创建表;
        CreateDBTable();
        //显示数据;
        showProcList(curDepartNo,curOrderNo,curStyleNo,curStyleID,curStyleSort,curWorkDate);
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }
    //创建数据库表
    private void CreateDBTable(){
        if (mainDB!=null) {
            //建表语句;
            System.out.println("CreateDBTable--------------Start");
            //员工表;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS EmpList (ID INTEGER PRIMARY KEY AUTOINCREMENT,DepartNo VARCHAR,EmpID VARCHAR,EmpNo VARCHAR, EmpName VARCHAR,EmpCT NUMERIC(8,2))");
            //员工工序表;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS EmpProcList (ID INTEGER PRIMARY KEY AUTOINCREMENT,DepartNo VARCHAR,EmpNo VARCHAR,OrderNo VARCHAR,StyleNo VARCHAR,StyleID VARCHAR," +
                    "StyleProID VARCHAR,StyleSort VARCHAR,WorkDate VARCHAR,WorkLineNo INTEGER,WorkNo VARCHAR,WorkName VARCHAR,MachineName VARCHAR,SlowTime INT,PlaceNo INT)");
            //工序表;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS ProcList (ID INTEGER PRIMARY KEY AUTOINCREMENT,DepartNo VARCHAR,OrderNo VARCHAR,StyleNo VARCHAR,StyleID VARCHAR,StyleSort VARCHAR,WorkDate VARCHAR,ArrangeID VARCHAR,SchemeID VARCHAR,ArrangeDeID VARCHAR,StyleProID VARCHAR," +
                    "PartIndex INTEGER,Part VARCHAR, WorkLineNo INTEGER,WorkNo VARCHAR,WorkName VARCHAR,MachineName VARCHAR,SlowTime INTEGER,WorkCT NUMERIC(8,2),WorkArrEmps VARCHAR,WorkArrEmpNos VARCHAR,PlaceNos VARCHAR,PlanEmpNum INTEGER,BaseKey VARCHAR)");
            //工序主表;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS ProcMaList (ID INTEGER PRIMARY KEY AUTOINCREMENT,ArrangeID VARCHAR,DepartNo VARCHAR,OrderNo VARCHAR,StyleNo VARCHAR,StyleID VARCHAR,StyleSort VARCHAR,WorkDate VARCHAR,OrderNumber INTEGER,SAMValue NUMERIC(8,2),TargetNum INTEGER,TT INTEGER," +
                    "CT NUMERIC(8,2),EmpCount INTEGER,BudgetOut INTEGER,BalanceRatio NUMERIC(8,2),UpdateTime DATETIME)");
            //临时表;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS EmpTotalCT (ID INTEGER PRIMARY KEY AUTOINCREMENT,DepartNo VARCHAR,EmpNo VARCHAR,OrderNo VARCHAR,StyleNo VARCHAR,StyleID VARCHAR,EmpCT NUMERIC(8,2))");
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS EmpTotalCount (ID INTEGER PRIMARY KEY AUTOINCREMENT,DepartNo VARCHAR,OrderNo VARCHAR,StyleNo VARCHAR,StyleID VARCHAR,StyleProID VARCHAR,WorkNo VARCHAR,EmpCount INTEGER)");
            //临时表用于暂存数据;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS DayNumList(ID INTEGER PRIMARY KEY AUTOINCREMENT,DayTitle VARCHAR,DayNum INT)");
            //读取配置文件;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS SetupTable (ID INTEGER PRIMARY KEY AUTOINCREMENT, KeyName VARCHAR,KeyValue VARCHAR)");
            //机台安排表;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS ArrangeMachine (ID INTEGER PRIMARY KEY AUTOINCREMENT,PlaceNo INT,EmpID VARCHAR,EmpNo VARCHAR,EmpName VARCHAR,WorkNames VARCHAR,MachineName VARCHAR)");
            //初始化机台表;
            mainDB.execSQL("Delete from ArrangeMachine");
            for (int i=1;i<=curPlaceCount;i++)
            {
                System.out.println("增加设备位:******-----------------------"+i+"-------------------------************");
                mainDB.execSQL("insert into ArrangeMachine(PlaceNO) values(?)",new Object[]{i});
            }
            System.out.println("CreateDBTable--------------End");
        }
    }
    //删除数据库
    private void dropAllTable(){
        if (mainDB!=null) {
            Log.d("Delete","删除数据库！");
            mainDB.execSQL("DROP TABLE IF EXISTS EmpList");
            mainDB.execSQL("DROP TABLE IF EXISTS EmpProcList");
            mainDB.execSQL("DROP TABLE IF EXISTS ProcList");
            mainDB.execSQL("DROP TABLE IF EXISTS ProcMaList");
            mainDB.execSQL("DROP TABLE IF EXISTS EmpTotalCT");
            mainDB.execSQL("DROP TABLE IF EXISTS EmpTotalCount");
            mainDB.execSQL("DROP TABLE IF EXISTS SetupTable");
            mainDB.execSQL("DROP TABLE IF EXISTS ArrangeMachine");
            mainDB.execSQL("DROP TABLE IF EXISTS DaliyCount");


        } else System.out.println("外部存储不可读写！");
    }

    //清除数据;
    private  void clearProcTable(){
        if (mainDB!=null) {
            Log.d("Delete","删除数据库！");
            mainDB.execSQL("DELETE FROM sqlite_sequence;");
            mainDB.execSQL("DELETE FROM EmpProcList");
            mainDB.execSQL("DELETE FROM ProcList");
            mainDB.execSQL("DELETE FROM ProcMaList");
            mainDB.execSQL("DELETE FROM EmpTotalCT");
            mainDB.execSQL("DELETE FROM EmpTotalCount");
            mainDB.execSQL("DELETE FROM SetupTable");
        }
    }

    //界面初始化;
    private void InitView(){
        txt_titleInv=(TextView)findViewById(R.id.txt_titleInv);
        txt_titleInv.setText(getString(R.string.procslipt));
        txt_titleInv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                AlertDialog alertDialog = new AlertDialog.Builder(v.getContext())
                        .setTitle(getString(R.string.SystemHint)).setMessage(getString(R.string.ClearAllData))
                        .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                //清空所有数据;
                                dropAllTable();
                            }

                        }).setNegativeButton(getString(R.string.Cancel),
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        return;
                                    }
                                }).create(); // 创建对话框
                alertDialog.show(); // 显示对话框
                return false;
            }
        });
        btn_LoginUser=(Button)findViewById(R.id.btn_LoginUser);
        btn_LoginUser.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                AlertDialog alertDialog = new AlertDialog.Builder(v.getContext())
                        .setTitle(getString(R.string.SystemHint)).setMessage(getString(R.string.CopyDataToExtStorage))
                        .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                //将临时文件复制到SD卡;
                                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                                    Log.d("MSG-getDatabasePath",getDatabasePath(DB_Name).toString());
                                    Log.d("MSG-getDataDirectory",getDataDirectory().toString());
                                    Log.d("MSG-StorageDirectory", getExternalStorageDirectory().toString());
                                    //将SD卡数据复制到数据目录;
                                    //copyFile(SaveFilePath+SaveDBFolder+"/"+DB_Name,getDatabasePath(DB_Name).toString());
                                    copyFile(getDatabasePath(DB_Name).toString(),SaveFilePath+SaveDBFolder+"/"+DB_Name);
                                }
                            }

                        }).setNegativeButton(getString(R.string.Cancel),
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        return;
                                    }
                                }).create(); // 创建对话框
                alertDialog.show(); // 显示对话框
                return false;
            }
        });
        btn_LoginClose=(Button)findViewById(R.id.btn_LoginClose);
        btn_LoginClose.setOnClickListener(this);
        //按键;
        btn_departRefresh=(Button)findViewById(R.id.btn_departRefresh);
        btn_departRefresh.setOnClickListener(this);
        Btn_ProcRefresh =(Button)findViewById(R.id.btn_ProcRefresh);
        Btn_ProcRefresh.setOnClickListener(this);
        btn_AddEmpProc=(Button)findViewById(R.id.btn_AddEmpProc);
        btn_AddEmpProc.setOnClickListener(this);
        btn_ClrEmpProc=(Button)findViewById(R.id.btn_ClrEmpProc);
        btn_ClrEmpProc.setOnClickListener(this);
        btn_ReArrangeProc=(Button)findViewById(R.id.btn_ReArrangeProc);
        btn_ReArrangeProc.setOnClickListener(this);
        btn_SaveProcScheme=(Button)findViewById(R.id.btn_SaveProcScheme);
        btn_SaveProcScheme.setOnClickListener(this);
        btn_ViewProcScheme=(Button)findViewById(R.id.btn_ViewProcScheme);
        btn_ViewProcScheme.setOnClickListener(this);
        btn_CopyArrangeProc=(Button)findViewById(R.id.btn_CopyArrangeProc);
        btn_CopyArrangeProc.setOnClickListener(this);
        btn_proc_switchPlace=(Button)findViewById(R.id.btn_proc_switchPlace);
        btn_proc_switchPlace.setOnClickListener(this);
        btn_proc_autoPlace=(Button)findViewById(R.id.btn_proc_autoPlace);
        btn_proc_autoPlace.setOnClickListener(this);
        //图片;
        image_StylePic=(ImageView)findViewById(R.id.image_StylePic);
        image_StylePic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String imgfilepath=getCacheDir()+"/"+ CurPhotoFileName;
                //将图片信息传出
                Intent imageActivity=new Intent(ProcsliptActivity.this,ImageActivity.class);
                //简单参数通过Intent的Extras传递;
                Bundle paramBundle = new Bundle();
                paramBundle.putString("PhotoUrl", imgfilepath);
                imageActivity.putExtras(paramBundle);
                //启动主界面;
                startActivity(imageActivity);
            }
        });
        //文本框
        text_SelPlaceNo =(TextView)findViewById(R.id.text_SelPlaceNo);
        text_SelEmpName=(TextView)findViewById(R.id.text_SelEmpName);
        text_titleFactory =(TextView)findViewById(R.id.text_titleFactory);
        text_titleDepart =(TextView)findViewById(R.id.text_titleDepart);
        text_titleEmpNum=(TextView)findViewById(R.id.text_titleEmpNum);
        edit_workDate=(EditText)findViewById(R.id.edit_workDate);
        edit_workDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {final Calendar calendar = Calendar.getInstance();
                final DatePickerDialog mDialog = new DatePickerDialog(ProcsliptActivity.this, null, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                mDialog .setButton(DialogInterface.BUTTON_POSITIVE,getString(R.string.Finish),new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDialog.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        calendar.set(year,month,day);
                        edit_workDate.setText(DateFormat.format("yyyy-MM-dd", calendar));
                    }
                });
                mDialog.setButton(DialogInterface.BUTTON_NEGATIVE,getString(R.string.Cancel),new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("cancel~~cancel~~");
                    }
                });
                mDialog.setTitle(getString(R.string.PleaseSelectQueryDate));
                mDialog.show();

            }
        });
        edit_workDate.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                curWorkDate=edit_workDate.getText().toString();

            }
        });
        text_titleOrderNo=(TextView)findViewById(R.id.text_titleOrderNo);
        text_titleStyleNo=(TextView)findViewById(R.id.text_titleStyleNo);
        text_titleNumber=(TextView)findViewById(R.id.text_titleNumber);
        text_titleSAMValue=(TextView)findViewById(R.id.text_titleSAMValue);
        text_titleTargetNum=(TextView)findViewById(R.id.text_titleTargetNum);
        text_titleTT=(TextView)findViewById(R.id.text_titleTT);
        text_ProcEmpCount=(TextView)findViewById(R.id.text_ProcEmpCount);
        text_ProcBudgetOut=(TextView)findViewById(R.id.text_ProcBudgetOut);
        text_ProcBalanceRatio=(TextView)findViewById(R.id.text_ProcBalanceRatio);

        //表格;
        procListView =(ListView)findViewById(R.id.procListView);
        procListView.setOnItemClickListener(this);
        procListView.setOnItemLongClickListener(this);
        empProcGrid=(GridView)findViewById(R.id.empProcGrid);
        empProcGrid.setOnItemClickListener(this);
        machineTotalGrid=(GridView)findViewById(R.id.machineTotalGrid);
        machineTotalGrid.setOnItemClickListener(this);
        //初始化;
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        empSidrBar=(SideBar)findViewById(R.id.empSidrBar);
        empDialog=(TextView)findViewById(R.id.empDialog);
        empSidrBar.setTextView(empDialog);
        empSidrBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                int position = empListAdapter.getPositionForSection(s.charAt(0));
                if(position != -1){
                    empListView.setSelection(position);
                }
            }
        });
        empListView=(ListView) findViewById(R.id.empListView);
        empListView.setOnItemClickListener(this);
        //排车表;
        arrMachineGrid=(GridView)findViewById(R.id.arrMachineGrid);
        arrMachineGrid.setOnItemClickListener(this);
        arrMachineGrid.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    selEmpNo = arrMachineList.optJSONObject(position).getString("EmpNo");
                    selEmpName = arrMachineList.optJSONObject(position).getString("EmpName");
                    selEmpID = arrMachineList.optJSONObject(position).getString("EmpID");
                    text_SelEmpName.setText(selEmpNo);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                AlertDialog alertDialog = new AlertDialog.Builder(view.getContext())
                        .setTitle(getString(R.string.SystemHint)).setMessage(getString(R.string.DelProcAffirmHint))
                        .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                //显示员工已安排工序;
                                showEmpProcList(curDepartNo, selEmpNo, curOrderNo, curStyleNo, curStyleID,curStyleSort);
                                //遍列位置对应的工序并选中;
                                try {
                                    for (int i=0;i<empProcList.length();i++) {
                                        String selWorkNo= null;
                                        selWorkNo = empProcList.getJSONObject(i).getString("WorkNo");
                                        Cursor cur=mainDB.rawQuery("Select WorkName from EmpProcList Where DepartNo=? AND EmpNo=? AND OrderNo=? AND StyleNo=?  and StyleSort=? and WorkNo=? and PlaceNo=? ",
                                                new String[]{curDepartNo,selEmpNo,curOrderNo,curStyleNo,curStyleSort,selWorkNo,selPlaceNo});
                                        if (cur.getCount()>0) empProcList.optJSONObject(i).put("SelSign", true);
                                        else empProcList.optJSONObject(i).put("SelSign", false);
                                    }
                                    //清除所有已选中的工序;
                                    ClrEmpProc(curDepartNo,curOrderNo,curStyleNo,curStyleID,curStyleSort);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                //更新显示;
                                ((BaseAdapter)empProcGrid.getAdapter()).notifyDataSetChanged();
                                //判断是否需要显示删除按钮;
                                checkEmpProcClrBtnState();

                            }

                        }).setNegativeButton(getString(R.string.Cancel),
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        return;
                                    }
                                }).create(); // 创建对话框
                alertDialog.show(); // 显示对话框
                return false;
            }
        });

        //置日期初始值;
        Date curDate = new Date(System.currentTimeMillis());
        edit_workDate.setText(DateFormat.format("yyyy-MM-dd", new Date(curDate.getTime())));

    }


    //统计车种数量;
    private void reTotalMachine(){
        try {
            TotalMachine=new JSONArray("[]");
            Cursor cur=mainDB.rawQuery("Select MachineName,count(1) as MachineCount from ArrangeMachine Group by MachineName",null);
            while (cur.moveToNext()){
                JSONObject machineJSON = new JSONObject();
                machineJSON.put("MachineName",cur.getString(cur.getColumnIndex("MachineName")));
                machineJSON.put("MachineCount",cur.getInt(cur.getColumnIndex("MachineCount")));
                TotalMachine.put(machineJSON);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            curToast.setText("重新统计衣车出错:\r\b"+e.getMessage());
            curToast.show();
        }
        //显示到arrMachineGrid中;
        final TotalMachineGridAdapter totalMachineGridAdapter=new TotalMachineGridAdapter(this);
        machineTotalGrid.setAdapter(totalMachineGridAdapter);
    }
    //显示员工数据;
    private void showArrMachineGrid(String paramDepartNo,String paramOrderNo,String paramStyleNo,String paramStyleID,String paramStyleSort)
    {
        System.out.println("showArrMachineGrid----------------------------->start");
        selPlaceNo="";
        int curPlaceNo=0;
        String empID="",empNo="",empName="",workNames="",machineName="";
        //更新当前款己安排SAM值;
        mainDB.execSQL("Update ArrangeMachine Set EmpID=?,EmpNo=?,EmpName=?,MachineName=?,WorkNames=?",new String[]{"","","","",""});
        //生成安排表;
        Cursor cur = mainDB.rawQuery("SELECT EmpList.EmpID,EmpList.EmpNo,EmpList.EmpName,EmpProcList.WorkLineNo,EmpProcList.WorkName,EmpProcList.MachineName,EmpProcList.PlaceNo FROM EmpList " +
                "inner join EmpProcList on EmpList.EmpNo=EmpProcList.EmpNo where EmpProcList.DepartNo=? and OrderNO=? and StyleNo=? and EmpProcList.StyleID=?" +
                "ORDER BY PlaceNo", new String[]{paramDepartNo,paramOrderNo,paramStyleNo,paramStyleID});
        System.out.println("paramDepartNo:"+paramDepartNo+" paramOrderNo:"+paramOrderNo+" paramStyleNo:"+paramStyleNo+" paramStyleID:"+paramStyleID+" RecCount:"+cur.getCount());
        while (cur.moveToNext()) {
            if (curPlaceNo!=cur.getInt(cur.getColumnIndex("PlaceNo")))
            {
                curPlaceNo=cur.getInt(cur.getColumnIndex("PlaceNo"));
                workNames="";
            }
            empID=cur.getString(cur.getColumnIndex("EmpID"));
            empNo=cur.getString(cur.getColumnIndex("EmpNo"));
            empName=cur.getString(cur.getColumnIndex("EmpName"));
            machineName=cur.getString(cur.getColumnIndex("MachineName"));
            String tmpWorkNo=cur.getString(cur.getColumnIndex("WorkLineNo"));
            String tmpWorkName=cur.getString(cur.getColumnIndex("WorkName"));
            if (tmpWorkName.length()>14) tmpWorkName=tmpWorkName.substring(0,14)+"...";
            if (workNames.length()>0) workNames=workNames+"\r\n"+tmpWorkNo+"."+tmpWorkName;else workNames=tmpWorkNo+"."+tmpWorkName;
            mainDB.execSQL("Update ArrangeMachine Set EmpID=?,EmpNo=?,EmpName=?,MachineName=?,WorkNames=? where PlaceNo=?",new Object[]{empID,empNo,empName,machineName,workNames,curPlaceNo});
        }
        System.out.println("showArrMachineGrid----------------------------->Middle");
        //将安排情况放入数组arrMachineList;
        cur = mainDB.rawQuery("SELECT * FROM ArrangeMachine ORDER BY PlaceNo",null);
        try {
            //初始化员工列表;
            arrMachineList=new JSONArray("[]");
            while (cur.moveToNext()) {
                JSONObject empJSON = new JSONObject();
                empJSON.put("SelSign",false);
                empJSON.put("PlaceNo",cur.getString(cur.getColumnIndex("PlaceNo")));
                empJSON.put("EmpID",cur.getString(cur.getColumnIndex("EmpID")));
                empJSON.put("EmpNo",cur.getString(cur.getColumnIndex("EmpNo")));
                empJSON.put("EmpName",cur.getString(cur.getColumnIndex("EmpName")));
                empJSON.put("MachineName", cur.getString(cur.getColumnIndex("MachineName")));
                empJSON.put("WorkNames", cur.getString(cur.getColumnIndex("WorkNames")));
                arrMachineList.put(empJSON);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.d("msg","创建arrMachineList----Json出错");
        }
        cur.close();
        System.out.println("showArrMachineGrid----------------------------->Over");
        //显示到arrMachineGrid中;
        final ArrMachineGridAdapter arrMachineGridAdapter=new ArrMachineGridAdapter(this);
        arrMachineGrid.setAdapter(arrMachineGridAdapter);
        //显示车种;
        reTotalMachine();
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }


    public final class ArrMachineGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public ArrMachineGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return arrMachineList.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return arrMachineList.get(position);
            } catch (JSONException e) {
                System.out.println("getItem取JSON数据出错!");
                e.printStackTrace();
                return  null;
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.procslipt_arrmachine_item, null, false);
            int ct_max_background = getResources().getColor(R.color.ct_max_background);
            int ct_nor_background = getResources().getColor(R.color.ct_nor_background);
            try {
                TextView tv = (TextView) convertView.findViewById(R.id.text_ArrMch_PlaceNo);// 显示文字
                tv.setText(arrMachineList.optJSONObject(position).get("PlaceNo").toString());
                tv = (TextView) convertView.findViewById(R.id.text_ArrMch_EmpName);// 显示文字
                tv.setText(arrMachineList.optJSONObject(position).get("EmpNo").toString());
                tv = (TextView) convertView.findViewById(R.id.text_ArrMch_WorkNames);// 显示文字
                tv.setText(arrMachineList.optJSONObject(position).get("WorkNames").toString());
                tv = (TextView) convertView.findViewById(R.id.text_ArrMch_MachineName);// 显示文字
                tv.setText(arrMachineList.optJSONObject(position).get("MachineName").toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.d("msg","ArrMachineGridAdapter_position:"+position);
            return convertView;
        }
    }


    //车种汇总;
    public final class TotalMachineGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public TotalMachineGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return TotalMachine.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return TotalMachine.get(position);
            } catch (JSONException e) {
                System.out.println("getItem取JSON数据出错!");
                e.printStackTrace();
                return  null;
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.procslipt_machinetotal_item, null, false);
            try {
                TextView tv = (TextView) convertView.findViewById(R.id.text_totalmachine_name);// 显示文字
                tv.setText(TotalMachine.optJSONObject(position).get("MachineName").toString());
                tv = (TextView) convertView.findViewById(R.id.text_totalmachine_count);// 显示文字
                tv.setText(TotalMachine.optJSONObject(position).get("MachineCount").toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.d("msg","TotalMachineGridAdapter_position:"+position);
            return convertView;
        }
    }

    /**
     * 为ListView填充数据
     * @return
     */
    private List<SortModel> filledEmpData(){
        List<SortModel> mSortList = new ArrayList<SortModel>();
        String sortString="";
        String pinyin="";
        for(int i=0; i<empList.length(); i++){
            SortModel sortModel = new SortModel();
            try {
                sortModel.setEmpID(empList.getJSONObject(i).getString("EmpID"));
                sortModel.setEmpName(empList.getJSONObject(i).getString("EmpName"));
                sortModel.setEmpNo(empList.getJSONObject(i).getString("EmpNo"));
                sortModel.setEmpCT(empList.getJSONObject(i).getInt("EmpCT"));
                sortModel.setSelSign("");
                //汉字转换成拼音
                pinyin = characterParser.getSelling(empList.getJSONObject(i).getString("EmpName"));
                sortString = pinyin.substring(0, 1).toUpperCase();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            // 正则表达式，判断首字母是否是英文字母
            if(sortString.matches("[A-Z]")){
                sortModel.setSortLetters(sortString.toUpperCase());
            }else{
                sortModel.setSortLetters("#");
            }
            mSortList.add(sortModel);
        }
        return mSortList;
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if (parent== procListView)
        {
            String StyleProcID="";
            String WorkNo="";
            String WorkName="";
            String BaseKey="";
            try {
                StyleProcID= procList.getJSONObject(position).getString("StyleProID");
                WorkNo=procList.getJSONObject(position).getString("WorkNo");
                WorkName=procList.getJSONObject(position).getString("WorkName");
                BaseKey=procList.getJSONObject(position).getString("BaseKey");
            } catch (JSONException e) {
                e.printStackTrace();
                curToast.setText(e.getMessage());
                curToast.show();
            }
            //创建布局
            LayoutInflater inflater=getLayoutInflater();
            final View proc_popmenu=inflater.inflate(R.layout.procslipt_popmenu, null);
            //Activity.findViewById最终还是会调用View.findViewById
            //因为在Activity的onCreate中一定会先setContentView的
            final Button btn_ProcMenu_SetAccProc=(Button)proc_popmenu.findViewById(R.id.btn_ProcMenu_SetAccProc);
            final Button btn_ProcMenu_SetPackProc=(Button)proc_popmenu.findViewById(R.id.btn_ProcMenu_SetPackProc);
            final Button btn_ProcMenu_ViewVideo=(Button)proc_popmenu.findViewById(R.id.btn_ProcMenu_ViewVideo);
            Log.d("BaseKey","BaseKey:"+BaseKey);
            btn_ProcMenu_SetAccProc.setEnabled(BaseKey.equals("false"));
            btn_ProcMenu_SetPackProc.setEnabled(BaseKey.equals("true"));
            final String finalStyleProcID = StyleProcID;
            final String finalWorkNo = WorkNo;
            final String finalWorkName = WorkName;
            //创建对话框
            final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
            builder.setView(proc_popmenu).setNegativeButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Log.v("tag",getString(R.string.Cancel));
                }
            });
            final Dialog dialog = builder.show();
            //菜单事件;
            btn_ProcMenu_SetAccProc.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setWorkProcToAcc(curDepartNo,curOrderNo,curStyleNo,curStyleID,finalStyleProcID,finalWorkNo,"辅料");
                    dialog.dismiss();
                }
            });
            btn_ProcMenu_SetPackProc.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setWorkProcToAcc(curDepartNo,curOrderNo,curStyleNo,curStyleID,finalStyleProcID,finalWorkNo,"大包");
                    dialog.dismiss();
                }
            });
            btn_ProcMenu_ViewVideo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
        }
        return false;
    }

    //设定工序为辅料或大包工序
    private void setWorkProcToAcc(String paramDepartNo,String paramOrderNo,String paramStyleNo,String paramStyleID,String paramStyleProcID,String paramWorkNo,String paramSetValue){
        waitDialog.setMessage(getString(R.string.SetAccWorkHint)+paramSetValue+"....");
        Log.d("setWorkProcToAcc","setWorkProcToAcc---------------Enter");
        //执行SQL过程
        String methodName="ExecSql";
        //通过哈希数组来传递参数;
        Map<String,Object> paramMap=new HashMap<String,Object>();
        //可传递多个参数  paramMap.put(paramName, paramValue);
        paramMap.put("SqlComm", "Exec ScenePAD_SetWorkProcType  @DepartmentNo='" + paramDepartNo + "',@OrderNo='"+paramOrderNo+"',@StyleNo='"+paramStyleNo+"',@StyleID='"+paramStyleID+"',@StyleProcID='"+paramStyleProcID+"',@WorkNo='"+paramWorkNo+"',@Type='"+paramSetValue+"',@UserNo='"+curLoginUserNo+"'");
        //调用WebService过程并处理界面更新;
        GetWebData(serviceUrl, methodName, paramMap);
        Log.d("setWorkProcToAcc","setWorkProcToAcc---------------Over");
    }
    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    // 显示手机键盘
    private void showIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.showSoftInputFromInputMethod(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    //显示员工数据;
    private void showEmpList(String paramDepart,String paramOrderNo,String paramStyleNo,String paramStyleID,String paramStyleSort)
    {
        selEmpID="";
        selEmpNo="";
        selEmpName="";
        //更新当前款己安排SAM值;
        mainDB.execSQL("update EmpList set EmpCT=0 where DepartNo=?",new String[]{paramDepart});
        mainDB.execSQL("Delete from EmpTotalCT");
        mainDB.execSQL("INSERT OR REPLACE INTO EmpTotalCT(DepartNo,EmpNo,OrderNo,StyleNo,EmpCT) Select DepartNo,EmpNo," +
                        "OrderNo,StyleNo,sum(SlowTime) EmpCT from EmpProcList where DepartNo=? and OrderNO=? and StyleNo=? Group by DepartNo,EmpNo,OrderNo,StyleNo",
                new String[]{paramDepart,paramOrderNo,paramStyleNo});
        mainDB.execSQL("update EmpList Set EmpCT=(select EmpCT from EmpTotalCT where EmpList.EmpNo=EmpTotalCT.EmpNo)");
        //将数据加载到empList中;
        Cursor cur = mainDB.rawQuery("SELECT * FROM EmpList where DepartNo=? ORDER BY ID", new String[]{paramDepart});
        //更新人数显示;
        Log.d("showEmpList","showEmpList----检查员工数量！");
        int empCount=cur.getCount();
        if (empCount==0)
        {
            refreshEmpList(paramDepart);
            return;
        }
        Log.d("showEmpList","showEmpList----准备显示员工！"+empCount);
        text_titleEmpNum.setText(String.valueOf(empCount)+getString(R.string.People));
        try {
            //初始化员工列表;
            empList=new JSONArray("[]");
            while (cur.moveToNext()) {
                JSONObject empJSON = new JSONObject();
                empJSON.put("EmpID",cur.getString(cur.getColumnIndex("EmpID")));
                empJSON.put("EmpNo",cur.getString(cur.getColumnIndex("EmpNo")));
                empJSON.put("EmpName", cur.getString(cur.getColumnIndex("EmpName")));
                empJSON.put("EmpCT", cur.getInt(cur.getColumnIndex("EmpCT")));
                empJSON.put("SelSign","");
                empList.put(empJSON);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.d("msg","创建empList----Json出错");
        }
        cur.close();
        //显示到emGrid中;
        SourceEmpList = filledEmpData();
        Collections.sort(SourceEmpList,pinyinComparator);
        empListAdapter=new SortAdapter(this,SourceEmpList);
        empListView.setAdapter(empListAdapter);
    }

    //重新获取员工工序列表;
    private void reGetEmpProcList(String paramDepartNo,String ParamEmpNo,String ParamOrderNo,String ParamStyleNo,String ParamStyleID,String paramStyleSort){
        //刷新当前员工已安排工序;
        //将数据加载到empList中;
        Cursor cur = mainDB.rawQuery("SELECT * FROM EmpProcList WHERE DepartNo=? AND EmpNo=? AND OrderNo=? AND StyleNo=?  and StyleSort=? ORDER BY WorkNo",new String[]{paramDepartNo,ParamEmpNo,ParamOrderNo,ParamStyleNo,paramStyleSort});
        try {
            //初始化工序列表;
            empProcList=new JSONArray("[]");
            while (cur.moveToNext()) {
                JSONObject empJSON = new JSONObject();
                empJSON.put("SelSign",false);
                empJSON.put("EmpNo",cur.getString(cur.getColumnIndex("EmpNo")));
                empJSON.put("OrderNo",cur.getString(cur.getColumnIndex("OrderNo")));
                empJSON.put("StyleNo",cur.getString(cur.getColumnIndex("StyleNo")));
                empJSON.put("StyleSort",cur.getString(cur.getColumnIndex("StyleSort")));
                empJSON.put("StyleProID",cur.getString(cur.getColumnIndex("StyleProID")));
                empJSON.put("WorkLineNo", cur.getString(cur.getColumnIndex("WorkLineNo")));
                empJSON.put("WorkNo", cur.getString(cur.getColumnIndex("WorkNo")));
                empJSON.put("WorkName", cur.getString(cur.getColumnIndex("WorkName")));
                empJSON.put("MachineName", cur.getString(cur.getColumnIndex("MachineName")));
                empJSON.put("SlowTime", cur.getString(cur.getColumnIndex("SlowTime")));
                empJSON.put("PlaceNo", cur.getString(cur.getColumnIndex("PlaceNo")));
                empProcList.put(empJSON);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.d("msg","empProcList----Json出错");
        }
        cur.close();
    }

    //员工已安排工序;
    private void showEmpProcList(String ParamDepartNo,String ParamEmpNo,String ParamOrderNo,String ParamStyleNo,String ParamStyleID,String ParamStyleSort) {
        reGetEmpProcList(ParamDepartNo,ParamEmpNo,ParamOrderNo,ParamStyleNo,ParamStyleID,ParamStyleSort);
        //显示到empProcGrid中;
        final EmpProcGridAdapter empProcGridAdapter=new EmpProcGridAdapter(this);
        empProcGrid.setAdapter(empProcGridAdapter);
        //检查按钮状态;
        checkEmpProcClrBtnState();
    }
    //显示工序数据;
    private void showProcList(String paramDepartNo,String paramOrderNo,String paramStyleNo,String paramStyleID,String paramStyleSort,String paramWorkDate)
    {
        System.out.println("showProcList------------------start");
        readyOrderNo=paramOrderNo;
        readyStyleNo=paramStyleNo;
        image_StylePic.setImageBitmap(null);
        CurPhotoFileName ="";
        System.out.println("showProcList------------------"+paramDepartNo+","+paramOrderNo+","+paramStyleNo+","+paramStyleID+","+paramStyleSort+","+paramWorkDate);
        //显示生产单相关信息;
        Cursor curma = mainDB.rawQuery("SELECT * FROM ProcMaList WHERE DepartNo=? and OrderNo=? and StyleNo=?  and StyleSort=? and WorkDate=? ORDER BY ID",
                new String[]{paramDepartNo,paramOrderNo,paramStyleNo,paramStyleSort,paramWorkDate});
        System.out.println("showProcList------------------b");
        if (curma.getCount()>0) {
            curma.moveToFirst();
            text_titleOrderNo.setText(curma.getString(curma.getColumnIndex("OrderNo")));
            text_titleStyleNo.setText(curma.getString(curma.getColumnIndex("StyleNo")));
            text_titleNumber.setText(curma.getString(curma.getColumnIndex("OrderNumber")));
            text_titleSAMValue.setText(curma.getString(curma.getColumnIndex("SAMValue")));
            text_titleTargetNum.setText(curma.getString(curma.getColumnIndex("TargetNum")));
            text_titleTT.setText(curma.getString(curma.getColumnIndex("TT")));
            curWorkTT=Integer.parseInt(curma.getString(curma.getColumnIndex("TT")));
            text_ProcEmpCount.setText(curma.getString(curma.getColumnIndex("EmpCount")));
            text_ProcBudgetOut.setText(curma.getString(curma.getColumnIndex("BudgetOut")));
            text_ProcBalanceRatio.setText(curma.getString(curma.getColumnIndex("BalanceRatio")));
        } else
        {
            curma.close();
            //刷新生产单;
            if (NeedReLoad==true) refreshProcList(paramDepartNo,paramOrderNo,paramStyleNo,paramStyleID,paramStyleSort,paramWorkDate);
            //后续不再执行;
            return;
        }
        curma.close();
        System.out.println("showProcList------------------1");
        //将数据加载到empList中;
        Cursor cur = mainDB.rawQuery("SELECT * FROM ProcList WHERE DepartNo=? and  OrderNo=? and StyleNo=? and StyleSort=? ORDER BY ID",
                new String[]{paramDepartNo,paramOrderNo,paramStyleNo,paramStyleSort});
        try {
            //初始化工序列表;
            procList=new JSONArray("[]");
            while (cur.moveToNext()) {
                JSONObject empJSON = new JSONObject();
                empJSON.put("ArrangeID",cur.getString(cur.getColumnIndex("ArrangeID")));
                empJSON.put("ArrangeDeID",cur.getString(cur.getColumnIndex("ArrangeDeID")));
                empJSON.put("SchemeID",cur.getString(cur.getColumnIndex("SchemeID")));
                empJSON.put("OrderNo", cur.getString(cur.getColumnIndex("OrderNo")));
                empJSON.put("StyleNo", cur.getString(cur.getColumnIndex("StyleNo")));
                empJSON.put("StyleID", cur.getString(cur.getColumnIndex("StyleID")));
                empJSON.put("StyleSort", cur.getString(cur.getColumnIndex("StyleSort")));
                empJSON.put("StyleProID", cur.getString(cur.getColumnIndex("StyleProID")));
                empJSON.put("Part", cur.getString(cur.getColumnIndex("Part")));
                empJSON.put("PartIndex", cur.getString(cur.getColumnIndex("PartIndex")));
                empJSON.put("WorkLineNo", cur.getString(cur.getColumnIndex("WorkLineNo")));
                empJSON.put("WorkNo", cur.getString(cur.getColumnIndex("WorkNo")));
                empJSON.put("WorkName", cur.getString(cur.getColumnIndex("WorkName")));
                empJSON.put("MachineName", cur.getString(cur.getColumnIndex("MachineName")));
                empJSON.put("SlowTime", cur.getString(cur.getColumnIndex("SlowTime")));
                empJSON.put("WorkCT", cur.getString(cur.getColumnIndex("WorkCT")));
                empJSON.put("WorkArrEmps", cur.getString(cur.getColumnIndex("WorkArrEmps")));
                empJSON.put("WorkArrEmpNos", cur.getString(cur.getColumnIndex("WorkArrEmpNos")));
                empJSON.put("PlaceNos",cur.getString(cur.getColumnIndex("PlaceNos")));
                empJSON.put("BaseKey",cur.getString(cur.getColumnIndex("BaseKey")));
                Log.d("showProcList","BaseKey:------->"+cur.getString(cur.getColumnIndex("BaseKey")));
                empJSON.put("SelSign",(Boolean)false);
                procList.put(empJSON);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            curToast.setText(e.getMessage());
            curToast.show();
            Log.d("msg","创建empList----Json出错");
        }
        System.out.println("showProcList------------------2");
        Log.d("msg","showProcList----记录条数为:"+cur.getCount());
        cur.close();
        //显示到工序中;
        final ProcGridAdapter procGridAdapter=new ProcGridAdapter(this);
        procListView.setAdapter(procGridAdapter);
        //显示完工序后、显示员工信息;
        Log.d("MSG","showProcList------------------------->showEmpList");
        showEmpList(curDepartNo,curOrderNo,curStyleNo,curStyleID,curStyleSort);
        //showImage(curDepartNo,curOrderNo,curStyleNo,curStyleID,curStyleSort);
        showArrMachineGrid(curDepartNo,curOrderNo,curStyleNo,curStyleID,curStyleSort);
    }
    //显示款式图片;
    private void showImage(String paramDepartNo,String paramOrderNo,String paramStyleNo,String paramStyleID,String paramStyleSort) {
        //获取MainActivity
        String imgfilepath=getCacheDir().toString();
        String imgfile=imgfilepath+"/"+paramStyleNo+".PNG";
        File file = new File(imgfile);
        //判断图片是否存在，如果不存在则从网络获取;
        if (file.exists()==true) {
            Log.d("showImage","准备从本地取图片显示---------------Start");
            //从本地取图片
            CurPhotoFileName =paramStyleNo+".PNG";
            Bitmap bitmap = getLoacalBitmap(imgfile);
            image_StylePic.setImageBitmap(bitmap);
        } else
        {
            waitDialog.setMessage(getString(R.string.FromNetGetPic));
            //从网页获取图片;
            String tmpServiceUrl=serviceUrl;
            //执行SQL过程
            String methodName="GetStyleImgURL";
            //通过哈希数组来传递参数;
            Map<String,Object> paramMap=new HashMap<String,Object>();
            //可传递多个参数  paramMap.put(paramName, paramValue);
            paramMap.put("paramDepartNo", paramDepartNo);
            paramMap.put("paramOrderNo",paramOrderNo);
            paramMap.put("paramStyleNo",paramStyleNo);
            paramMap.put("paramStyleID",paramStyleID);
            paramMap.put("paramStyleSort",paramStyleSort);
            //调用WebService过程并处理界面更新;
            GetWebData(tmpServiceUrl, methodName, paramMap);
            Log.d("showImage","准备从网页获取图片---------------Start");
        }
    }

    //显示工序安排;
    private void showArrangeActivity(){
        //将登陆信息、车间、组别、工作时间等信息带过去。
        Intent arrangeActivity=new Intent(this,ArrangeActivity.class);
        //简单参数通过Intent的Extras传递;
        Bundle paramBundle = new Bundle();
        paramBundle.putString("DepartNo", curDepartNo);
        paramBundle.putString("OrderNo", curOrderNo);
        paramBundle.putString("StyleNo", curStyleNo);
        paramBundle.putString("StyleID", curStyleID);
        paramBundle.putString("StyleSort",curStyleSort);
        paramBundle.putString("serviceUrl",serviceUrl);
        paramBundle.putInt("TT", curWorkTT);
        arrangeActivity.putExtras(paramBundle);
        //启动主界面;
        startActivity(arrangeActivity);
    }
    //刷新员工列表;
    private void refreshEmpList(String departParam)
    {
        waitDialog.setMessage(getString(R.string.FromNetGetEmpInfo));
        Log.d("refreshEmpList","refreshEmpList---------------Enter");
        //执行SQL过程
        String methodName="ExecSql";
        //通过哈希数组来传递参数;
        Map<String,Object> paramMap=new HashMap<String,Object>();
        //可传递多个参数  paramMap.put(paramName, paramValue);
        paramMap.put("SqlComm", "Exec ScenePAD_GetEmpList  @DepartmentNo='" + departParam + "',@GetContext=1");
        //调用WebService过程并处理界面更新;
        ReadEmpSQLData(serviceUrl, methodName, paramMap);
        Log.d("refreshEmpList","refreshEmpList---------------Over");
    }


    //刷新订单列表;
    private void refreshOrderList(String departParam,String orderParam,String styleParam,String SortParam)
    {
        selectStyleID="";
        selectOrderNo ="";
        selectStyleNo="";
        //清空原订单记录;
        try {
            OrderJSONArray=new JSONArray("[]");
            //显示到工序中;
            final SelectOrderListAdapter selectOrderListAdapter=new SelectOrderListAdapter(this);
            procOrderListGrid.setAdapter(selectOrderListAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NeedReLoad=false;
        waitDialog.setMessage(getString(R.string.FromNetGetOrderInfo));
        //执行SQL过程
        String methodName="ExecSql";
        //通过哈希数组来传递参数;
        Map<String,Object> paramMap=new HashMap<String,Object>();
        //可传递多个参数  paramMap.put(paramName, paramValue);
        paramMap.put("SqlComm", "Exec ScenePAD_GetSelectOrder @DepartNo='" + departParam + "',@OrderNo='"+orderParam+"',@StyleNo='"+styleParam+"',@StyleSort='"+SortParam+"',@UserNo='"+curLoginUserNo+"'");
        //调用WebService过程并处理界面更新;
        System.out.println(paramMap);
        ReadSQLData(serviceUrl, methodName, paramMap);
    }

    //复制安排表;
    private void  CopyStyleArrange(String ParamDepartNo,String ParamTarOrderNo,String ParamTarStyleNo,String ParamTarStyleSort,String ParamTarStyleID,String  ParamSurOrderNO,String ParamSurStyleNo,String ParamSurStyleID,String paramSurStyleSort){
        System.out.println("CopyStyleArrange");
        waitDialog.setMessage(getString(R.string.RequestServerCopyProc));
        //执行SQL过程
        String methodName="ExecSql";
        //通过哈希数组来传递参数;
        Map<String,Object> paramMap=new HashMap<String,Object>();
        //可传递多个参数  paramMap.put(paramName, paramValue);
        paramMap.put("SqlComm", "Exec ScenePAD_CopyStyleArrange @DepartNo='" + ParamDepartNo + "',@TarOrderNo='"+ParamTarOrderNo+"',@TarStyleNo='"+ParamTarStyleNo+"',@TarStyleSort='"+ParamTarStyleSort+"',@TarStyleID='"+ParamTarStyleID
                +"',@SurOrderNo='"+ParamSurOrderNO+"',@SurStyleNo='"+ParamSurStyleNo+"',@SurStyleID='"+ParamSurStyleID+"',@SurStyleSort='"+paramSurStyleSort+"',@UserNo='"+curLoginUserNo+"'");
        System.out.println(paramMap);
        //调用WebService过程并处理界面更新;
        ReadSQLData(serviceUrl, methodName, paramMap);
    }
    //显示可以复制的订单列表;
    private void showOrderList() {
        //显示到工序中;
        final SelectOrderListAdapter selectOrderListAdapter=new SelectOrderListAdapter(this);
        procOrderListGrid.setAdapter(selectOrderListAdapter);
    }

    //刷新工序列表;
    private void refreshProcList(String departParam,String orderParam,String styleParam,String paramStyleID,String paramStyleSort,String paramWorkDate)
    {
        //清空数据;
        clearProcTable();
        //重新加载，永远只保留一个款的各个日期的数据
        NeedReLoad=false;
        waitDialog.setMessage(getString(R.string.FromNetGetProcInfo));
        //执行SQL过程
        String methodName="ExecSql";
        //通过哈希数组来传递参数;
        Map<String,Object> paramMap=new HashMap<String,Object>();
        //可传递多个参数  paramMap.put(paramName, paramValue);
        paramMap.put("SqlComm", "Exec ScenePAD_GetProcList @DepartmentNo='" + departParam + "',@OrderNo='"+orderParam+"',@StyleNo='"+styleParam
                +"',@StyleID='"+paramStyleID+"',@StyleSort='"+paramStyleSort+"',@WorkDate='"+paramWorkDate+"'");
        //调用WebService过程并处理界面更新;
        ReadProcSQLData(serviceUrl, methodName, paramMap);
    }

    public void ReadEmpSQLData(String serviceUrl, String methodName, Map<String,Object> paramMap) {
        //组织参数传到匿名类中;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("serviceUrl",serviceUrl);
        params.put("methodName",methodName);
        params.put("paramMap",paramMap);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String,Object>,Void,String>()
        {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                waitDialog.show();
            }

            @Override
            protected String doInBackground(Map<String, Object>... params) {
                boolean ErrSign=false;
                String serviceUrl= (String) params[0].get("serviceUrl");
                System.out.println(serviceUrl);
                String methodName= (String) params[0].get("methodName");
                //置参数给对象
                String namespace="http://tempuri.org/";
                SoapObject soapObject=new SoapObject(namespace, methodName);
                SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
                //遍列Map数组加参数
                Map<String,Object> paramMap= (Map<String,Object>) params[0].get("paramMap");
                Iterator iterator = paramMap.keySet().iterator();
                while (iterator.hasNext())
                {
                    String paramkey = (String) iterator.next();
                    String paramvalue = (String) paramMap.get(paramkey);
                    soapObject.addProperty(paramkey,paramvalue);//带参数的方法调用，若调用无参数的，则无需此句
                }
                //准备执行WebService
                envelope.dotNet=true;
                envelope.setOutputSoapObject(soapObject);
                HttpTransportSE httpTranstation=new HttpTransportSE(serviceUrl,10000);
                try {
                    //执行调用WebService;
                    httpTranstation.call(namespace+methodName, envelope);
                    //获取返回会值;
                    Object result=envelope.getResponse();
                    //将获取的返回值转成字符串
                    String resultstr=(String) result.toString();
                    System.out.println(resultstr);
                    //字符串数据直接返回，由回调函数OnPostExecute中进行UI刷新显示;
                    return resultstr;
                } catch (HttpResponseException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (SoapFault soapFault) {
                    ErrSign=true;
                    soapFault.printStackTrace();
                } catch (XmlPullParserException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (IOException e) {
                    ErrSign=true;
                    e.printStackTrace();
                }
                //关闭刷新窗口;
                if (ErrSign==true) waitDialog.hide();
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if (s==null) return;
                //这部分主要用于UI更新;
                try {
                    //字符串转JSON序列;
                    /*
                    //如果返回的格式中有键值[data:{name:aa arg:12}{name:aa arg:12}{name:aa arg:12}]
                    JSONObject obj = new JSONObject(result.toString());
                    JSONArray jsonArray = (JSONArray)obj.getJSONArray("data");
                    */
                    //返回的格式如[{name:aa arg:12}{name:aa arg:12}{name:aa arg:12}]则直接转换即可
                    Log.d("ReadEmpSQLData","onPostExecute------------------------->showEmpList:0");
                    System.out.println("接收到的内容:"+s);
                    JSONArray jsonArray = new JSONArray(s);
                    if (jsonArray.length()>0) {
                        //将数据存到数据库中;
                        mainDB.execSQL("Delete from EmpList");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            mainDB.execSQL("INSERT INTO EmpList(ID,DepartNo,EmpID,EmpNo,EmpName) VALUES (NULL,?,?,?,?)", new Object[]{jsonArray.optJSONObject(i).getString("DepartNo"), jsonArray.optJSONObject(i).getString("EmpID"), jsonArray.optJSONObject(i).getString("EmpNo"), jsonArray.optJSONObject(i).getString("EmpName")});
                        }
                        waitDialog.hide();
                        //显示数据;
                        showEmpList(curDepartNo,curOrderNo,curStyleNo,curStyleID,curStyleSort);
                    } else
                    {
                        waitDialog.hide();
                        Log.d("ReadEmpSQLData","onPostExecute------------------------->showEmpList:2");
                        //清空数据;
                        empList=new JSONArray("[]");
                        //显示到empListView中;
                        SourceEmpList = filledEmpData();
                        Collections.sort(SourceEmpList,pinyinComparator);
                        empListAdapter=new SortAdapter(ProcsliptActivity.this,SourceEmpList);
                        empListView.setAdapter(empListAdapter);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    waitDialog.hide();
                    curToast.setText(e.getMessage());
                    curToast.show();
                }
            }
        }.execute(params);

    }


    public void ReadSQLData(String serviceUrl,String methodName,Map<String,Object> paramMap) {
        //组织参数传到匿名类中;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("serviceUrl",serviceUrl);
        params.put("methodName",methodName);
        params.put("paramMap",paramMap);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String,Object>,Void,String>()
        {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                waitDialog.show();
            }

            @Override
            protected String doInBackground(Map<String, Object>... params) {
                Boolean ErrSign=false;
                String serviceUrl= (String) params[0].get("serviceUrl");
                System.out.println("ReadSQLData:"+serviceUrl);
                String methodName= (String) params[0].get("methodName");
                try {
                    //置参数给对象
                    String namespace = "http://tempuri.org/";
                    SoapObject soapObject = new SoapObject(namespace, methodName);
                    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                    //遍列Map数组加参数
                    Map<String, Object> paramMap = (Map<String, Object>) params[0].get("paramMap");
                    Iterator iterator = paramMap.keySet().iterator();
                    while (iterator.hasNext()) {
                        String paramkey = (String) iterator.next();
                        String paramvalue = (String) paramMap.get(paramkey);
                        soapObject.addProperty(paramkey, paramvalue);//带参数的方法调用，若调用无参数的，则无需此句
                    }
                    //准备执行WebService
                    envelope.dotNet = true;
                    envelope.setOutputSoapObject(soapObject);

                    HttpTransportSE httpTranstation = new HttpTransportSE(serviceUrl, 10000);
                    //执行调用WebService;
                    httpTranstation.call(namespace + methodName, envelope);
                    //获取返回会值;
                    Object result = envelope.getResponse();
                    //将获取的返回值转成字符串
                    String resultstr = (String) result.toString();
                    System.out.println(resultstr);
                    //字符串数据直接返回，由回调函数OnPostExecute中进行UI刷新显示;
                    return resultstr;
                } catch (HttpResponseException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (SoapFault soapFault) {
                    ErrSign=true;
                    soapFault.printStackTrace();
                } catch (XmlPullParserException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (IOException e) {
                    ErrSign=true;
                    e.printStackTrace();
                }catch (Exception e){
                    ErrSign=true;
                }
                //关闭ProgressDialog
                if (ErrSign==true) {
                    Log.d("msg","查询数据出错,错误异常抛出！");
                    waitDialog.hide();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if (s==null) return;
                //这部分主要用于UI更新;
                try {
                    //字符串转JSON序列;
                    /*
                    //如果返回的格式中有键值[data:{name:aa arg:12}{name:aa arg:12}{name:aa arg:12}]
                    JSONObject obj = new JSONObject(result.toString());
                    JSONArray jsonArray = (JSONArray)obj.getJSONArray("data");
                    */
                    //返回的格式如[{name:aa arg:12}{name:aa arg:12}{name:aa arg:12}]则直接转换即可
                    System.out.println("接收到的内容:"+s);
                    JSONArray jsonArray = new JSONArray(s);
                    //往界面转数据;
                    if (jsonArray.length()>0)
                    {
                        Log.d("msg","onPostExecute--------------------1");
                        //返回的为订单数据;
                        if (jsonArray.optJSONObject(0).has("GetSelectOrder")==true)
                        {
                            Log.d("msg","GetSelectOrder--------------------2");
                            OrderJSONArray=jsonArray;
                            //显示明细数据;
                            showOrderList();
                        }
                        //返回的为订单数据;
                        if (jsonArray.optJSONObject(0).has("CopyStyleArrange")==true)
                        {
                            Log.d("msg","CopyStyleArrange--------------------2");
                            String resultMsg = jsonArray.optJSONObject(0).getString("CopyStyleArrange");
                            // 创建对话框
                            AlertDialog alertDialog = new AlertDialog.Builder(ProcsliptActivity.this)
                                    .setTitle(getString(R.string.SystemHint)).setMessage(resultMsg)
                                    .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                        }
                                    }).create();
                            alertDialog.show(); // 显示对话框
                            //刷新工序;
                            showProcList(curDepartNo,curOrderNo,curStyleNo,curStyleID,curStyleSort,curWorkDate);
                        }

                    }

                    //关闭ProgressDialog
                    waitDialog.hide();
                } catch (JSONException e) {
                    e.printStackTrace();
                    //关闭ProgressDialog
                    waitDialog.hide();
                    curToast.setText(e.getMessage());
                    curToast.show();
                }
            }
        }.execute(params);

    }

    public void ReadProcSQLData(String serviceUrl,String methodName,Map<String,Object> paramMap) {
        //组织参数传到匿名类中;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("serviceUrl",serviceUrl);
        params.put("methodName",methodName);
        params.put("paramMap",paramMap);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String,Object>,Void,String>()
        {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                waitDialog.show();
            }

            @Override
            protected String doInBackground(Map<String, Object>... params) {
                boolean ErrSign=false;
                try {
                    String serviceUrl= (String) params[0].get("serviceUrl");
                    System.out.println(serviceUrl);
                    String methodName= (String) params[0].get("methodName");
                    //置参数给对象
                    String namespace="http://tempuri.org/";
                    SoapObject soapObject=new SoapObject(namespace, methodName);
                    SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
                    //遍列Map数组加参数
                    Map<String,Object> paramMap= (Map<String,Object>) params[0].get("paramMap");
                    Iterator iterator = paramMap.keySet().iterator();
                    while (iterator.hasNext())
                    {
                        String paramkey = (String) iterator.next();
                        String paramvalue = (String) paramMap.get(paramkey);
                        soapObject.addProperty(paramkey,paramvalue);//带参数的方法调用，若调用无参数的，则无需此句
                    }
                    //准备执行WebService
                    envelope.dotNet=true;
                    envelope.setOutputSoapObject(soapObject);
                    HttpTransportSE httpTranstation=new HttpTransportSE(serviceUrl,10000);
                    //执行调用WebService;
                    httpTranstation.call(namespace+methodName, envelope);
                    //获取返回会值;
                    Object result=envelope.getResponse();
                    //将获取的返回值转成字符串
                    String resultstr=(String) result.toString();
                    //字符串数据直接返回，由回调函数OnPostExecute中进行UI刷新显示;
                    return resultstr;
                } catch (HttpResponseException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (SoapFault soapFault) {
                    ErrSign=true;
                    soapFault.printStackTrace();
                } catch (XmlPullParserException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (IOException e) {
                    ErrSign=true;
                    e.printStackTrace();
                }
                //关闭ProgressDialog
                if (ErrSign==true) {
                    Log.d("msg","查询数据出错,错误异常抛出！");
                }
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if (s==null)
                {
                    if (waitDialog.equals(null)==false) waitDialog.hide();
                    return;
                }
                //这部分主要用于UI更新;
                try {
                    //字符串转JSON序列;
                    /*
                    //如果返回的格式中有键值[data:{name:aa arg:12}{name:aa arg:12}{name:aa arg:12}]
                    JSONObject obj = new JSONObject(result.toString());
                    JSONArray jsonArray = (JSONArray)obj.getJSONArray("data");
                    */
                    //返回的格式如[{name:aa arg:12}{name:aa arg:12}{name:aa arg:12}]则直接转换即可
                    System.out.println("接收到的内容:"+s);
                    //将数据存到数据库中;
                    mainDB.execSQL("Delete from ProcMaList where DepartNo=? and OrderNo=? AND StyleNo=? ", new String[]{curDepartNo,curOrderNo, curStyleNo});
                    mainDB.execSQL("Delete from ProcList where DepartNo=? and OrderNo=? AND StyleNo=? ", new String[]{curDepartNo,curOrderNo, curStyleNo});
                    mainDB.execSQL("Delete from EmpProcList where DepartNo=? and OrderNo=? AND StyleNo=? ", new String[]{curDepartNo,curOrderNo, curStyleNo});
                    //转换数据;
                    JSONArray jsonArray = new JSONArray(s);
                    if (jsonArray.length()>0) {
                        Log.d("msg","onPostExecute:jsonArray长度为"+jsonArray.length()+"，准备转换。。。。。。。。");
                        //往界面转数据;
                        OrderJSONArray = jsonArray;
                        //生成ProcMaList记录;
                        mainDB.execSQL("INSERT INTO ProcMaList(ArrangeID,DepartNo,OrderNo,StyleNo,StyleID,StyleSort,WorkDate,OrderNumber,SAMValue,TargetNum,TT,CT,EmpCount,BudgetOut,BalanceRatio,UpdateTime)" +
                                        " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,datetime('now','localtime'))",
                                new Object[]{OrderJSONArray.optJSONObject(0).getString("ArrangeID"), OrderJSONArray.optJSONObject(0).getString("DepartNo")
                                        , OrderJSONArray.optJSONObject(0).getString("OrderNo"), OrderJSONArray.optJSONObject(0).getString("StyleNo")
                                        , OrderJSONArray.optJSONObject(0).getString("StyleID"), OrderJSONArray.optJSONObject(0).getString("StyleSort"), OrderJSONArray.optJSONObject(0).getString("WorkDate")
                                        , OrderJSONArray.optJSONObject(0).getInt("OrderNumber"), OrderJSONArray.optJSONObject(0).getLong("SAMValue")
                                        , OrderJSONArray.optJSONObject(0).getInt("TargetNum"), OrderJSONArray.optJSONObject(0).getInt("TT")
                                        , OrderJSONArray.optJSONObject(0).getDouble("CT"), OrderJSONArray.optJSONObject(0).getInt("EmpCount")
                                        , OrderJSONArray.optJSONObject(0).getInt("BudgetOut"), OrderJSONArray.optJSONObject(0).getLong("BalanceRatio")});
                        Log.d("msg","onPostExecute:生成ProcMaList记录完成...........");

                        //保存相关记录;
                        for (int i = 0; i < OrderJSONArray.length(); i++) {
                            //保存工序数据;
                            mainDB.execSQL("INSERT INTO ProcList(ArrangeID,ArrangeDeID,SchemeID,DepartNo,OrderNo,StyleNo,StyleID,StyleSort,WorkDate,StyleProID,Part,PartIndex,WorkLineNo,WorkNo,WorkName,MachineName,SlowTime,WorkCT,WorkArrEmps,WorkArrEmpNos,PlaceNos,BaseKey) " +
                                            "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                                    new Object[]{OrderJSONArray.optJSONObject(i).getString("ArrangeID"), OrderJSONArray.optJSONObject(i).getString("ArrangeDeID")
                                            , OrderJSONArray.optJSONObject(i).getString("SchemeID")
                                            , OrderJSONArray.optJSONObject(i).getString("DepartNo"), OrderJSONArray.optJSONObject(i).getString("OrderNo")
                                            , OrderJSONArray.optJSONObject(i).getString("StyleNo"), OrderJSONArray.optJSONObject(i).getString("StyleID")
                                            , OrderJSONArray.optJSONObject(i).getString("StyleSort"), OrderJSONArray.optJSONObject(i).getString("WorkDate")
                                            , OrderJSONArray.optJSONObject(i).getString("StyleProID"), OrderJSONArray.optJSONObject(i).getString("Part")
                                            , OrderJSONArray.optJSONObject(i).getString("PartIndex"), OrderJSONArray.optJSONObject(i).getString("WorkLineNo")
                                            , OrderJSONArray.optJSONObject(i).getString("WorkNo")
                                            , OrderJSONArray.optJSONObject(i).getString("WorkName"), OrderJSONArray.optJSONObject(i).getString("MachineName")
                                            , OrderJSONArray.optJSONObject(i).getString("SlowTime"), OrderJSONArray.optJSONObject(i).getString("WorkCT")
                                            , OrderJSONArray.optJSONObject(i).getString("WorkArrEmps"), OrderJSONArray.optJSONObject(i).getString("WorkArrEmpNos")
                                            ,OrderJSONArray.optJSONObject(i).getString("PlaceNos"),(OrderJSONArray.optJSONObject(i).get("BaseKey").equals(null)?"false": OrderJSONArray.optJSONObject(i).getString("BaseKey"))
                                    });
                            //保存安排数据
                            String WorkArrEmpNos = (OrderJSONArray.optJSONObject(i).get("WorkArrEmpNos").equals(null)?"": OrderJSONArray.optJSONObject(i).getString("WorkArrEmpNos"));
                            String WorkArrPlaceNos=(OrderJSONArray.optJSONObject(i).getString("PlaceNos").equals(null)?"": OrderJSONArray.optJSONObject(i).getString("PlaceNos"));
                            String[] ArrEmpNos = null;
                            String[] ArrPlaceNos = null;
                            ArrEmpNos = WorkArrEmpNos.split(",");
                            ArrPlaceNos = WorkArrPlaceNos.split(",");
                            String placeNo="0";
                            if (!ArrEmpNos.equals(null)) {
                                for (int j = 0; j < ArrEmpNos.length; j++) {
                                    //长度为0的也会分解成长度为1的数据;
                                    if (ArrEmpNos[j].length()>0) {
                                        if (ArrPlaceNos.length > j) placeNo = ArrPlaceNos[j];
                                        else placeNo = "0";
                                        mainDB.execSQL("INSERT INTO EmpProcList(DepartNo,EmpNo,OrderNo,StyleNo,StyleID,StyleSort,WorkDate,StyleProID,WorkLineNo,WorkNo,WorkName,MachineName,SlowTime,PlaceNo) " +
                                                        "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                                                new Object[]{OrderJSONArray.optJSONObject(i).getString("DepartNo"), ArrEmpNos[j], OrderJSONArray.optJSONObject(i).getString("OrderNo")
                                                        , OrderJSONArray.optJSONObject(i).getString("StyleNo"), OrderJSONArray.optJSONObject(i).getString("StyleID")
                                                        , OrderJSONArray.optJSONObject(i).getString("StyleSort"), OrderJSONArray.optJSONObject(i).getString("WorkDate")
                                                        , OrderJSONArray.optJSONObject(i).getString("StyleProID"), OrderJSONArray.optJSONObject(i).getInt("WorkLineNo")
                                                        , OrderJSONArray.optJSONObject(i).getString("WorkNo"), OrderJSONArray.optJSONObject(i).getString("WorkName")
                                                        , OrderJSONArray.optJSONObject(i).getString("MachineName"), OrderJSONArray.optJSONObject(i).getInt("SlowTime"), placeNo});
                                    }
                                }
                            }
                        }
                        Log.d("msg","onPostExecute:转换完成.......准备显示工序");
                        //显示数据,不能放到外面，会引起死循环;
                        showProcList(curDepartNo,curOrderNo, curStyleNo,curStyleID,curStyleSort,curWorkDate);
                        //更新平衡率及工作人数;
                        updateBudgetOut(curDepartNo,curOrderNo,curStyleNo,curStyleID);
                    } else
                    {
                        //如果没有数据，则
                        //清空数据;
                        procList=new JSONArray("[]");
                        empProcList=new JSONArray("[]");
                        //显示员工;
                        showEmpList(curDepartNo,curOrderNo,curStyleNo,curStyleID,curStyleSort);
                        //显示到procGrid中;
                        final ProcGridAdapter procGridAdapter=new ProcGridAdapter(ProcsliptActivity.this);
                        procListView.setAdapter(procGridAdapter);
                        //显示到员工工序表empProcGrid中;
                        final EmpProcGridAdapter empGridAdapter=new EmpProcGridAdapter(ProcsliptActivity.this);
                        empProcGrid.setAdapter(empGridAdapter);
                    }
                    Log.d("msg","onPostExecute转换完成，准备显示。。。。。。。。");
                    //关闭ProgressDialog
                    waitDialog.hide();
                } catch (JSONException e) {
                    e.printStackTrace();
                    waitDialog.hide();
                    curToast.setText(e.getMessage());
                    curToast.show();
                }
            }
        }.execute(params);

    }

    public void GetWebData(final String serviceUrl, String methodName, Map<String,Object> paramMap) {
        final Context thisContent=this;
        //组织参数传到匿名类中;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("serviceUrl",serviceUrl);
        params.put("methodName",methodName);
        params.put("paramMap",paramMap);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String,Object>,Void,String>()
        {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                waitDialog.show();
            }

            @Override
            protected String doInBackground(Map<String, Object>... params) {
                boolean ErrSign=false;
                try {
                    String serviceUrl= (String) params[0].get("serviceUrl");
                    System.out.println(serviceUrl);
                    String methodName= (String) params[0].get("methodName");
                    //置参数给对象
                    String namespace = "http://tempuri.org/";
                    SoapObject soapObject = new SoapObject(namespace, methodName);
                    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                    //遍列Map数组加参数
                    Map<String, Object> paramMap = (Map<String, Object>) params[0].get("paramMap");
                    Iterator iterator = paramMap.keySet().iterator();
                    while (iterator.hasNext()) {
                        String paramkey = (String) iterator.next();
                        String paramvalue = (String) paramMap.get(paramkey);
                        soapObject.addProperty(paramkey, paramvalue);//带参数的方法调用，若调用无参数的，则无需此句
                    }
                    //准备执行WebService
                    envelope.dotNet = true;
                    envelope.setOutputSoapObject(soapObject);
                    HttpTransportSE httpTranstation = new HttpTransportSE(serviceUrl, 10000);

                    //执行调用WebService;
                    httpTranstation.call(namespace + methodName, envelope);
                    //获取返回会值;
                    Object result = envelope.getResponse();
                    //将获取的返回值转成字符串
                    String resultstr = (String) result.toString();
                    //字符串数据直接返回，由回调函数OnPostExecute中进行UI刷新显示;
                    return resultstr;
                } catch (HttpResponseException e) {
                    ErrSign=true;
                    e.printStackTrace();
                    curToast.setText("A."+getString(R.string.ServerErrPlsConManager)+"\r\n"+e.getMessage());
                    curToast.show();
                } catch (SoapFault e) {
                    ErrSign=true;
                    e.printStackTrace();
                    curToast.setText("B."+getString(R.string.ServerErrPlsConManager)+"\r\n"+e.getMessage());
                    curToast.show();
                } catch (XmlPullParserException e) {
                    ErrSign=true;
                    e.printStackTrace();
                    curToast.setText("C."+getString(R.string.ServerErrPlsConManager)+"\r\n"+e.getMessage());
                    curToast.show();
                } catch (SocketTimeoutException e){
                    ErrSign=true;
                    e.printStackTrace();
                    curToast.setText("D."+getString(R.string.ServerErrPlsConManager)+"\r\n"+e.getMessage());
                    curToast.show();
                } catch (IOException e) {
                    ErrSign=true;
                    e.printStackTrace();
                    curToast.setText("E."+getString(R.string.ServerErrPlsConManager)+"\r\n"+e.getMessage());
                    curToast.show();
                }
                //关闭ProgressDialog
                if (ErrSign==true) {
                    Log.d("msg","查询数据出错,错误异常抛出！");
                }
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                System.out.println("----------------------------onPostExecute----------------------------");
                if (s==null)
                {
                    if (waitDialog.equals(null)==false) waitDialog.hide();
                    return;
                }
                //这部分主要用于UI更新;
                try {
                    //字符串转JSON序列;
                    /*
                    //如果返回的格式中有键值[data:{name:aa arg:12}{name:aa arg:12}{name:aa arg:12}]
                    JSONObject obj = new JSONObject(result.toString());
                    JSONArray jsonArray = (JSONArray)obj.getJSONArray("data");
                    */
                    //返回的格式如[{name:aa arg:12}{name:aa arg:12}{name:aa arg:12}]则直接转换即可
                    System.out.println("接收到的内容:"+s);
                    waitDialog.hide();//收到信息后取消提示;
                    //转换数据;
                    JSONArray jsonArray = new JSONArray(s);
                    if (jsonArray.length()>0) {
                        if (jsonArray.getJSONObject(0).has("PROCRESULT")==true) {
                            String resultMsg = jsonArray.optJSONObject(0).getString("PROCRESULT");
                            //提示提交完成，需确认;
                            // 创建对话框
                            AlertDialog alertDialog = new AlertDialog.Builder(ProcsliptActivity.this)
                                    .setTitle(getString(R.string.SystemHint)).setMessage(resultMsg)
                                    .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                        }
                                    }).create();
                            alertDialog.show(); // 显示对话框
                        }
                        //取图片路径;
                        if (jsonArray.getJSONObject(0).has("StyleImgURL")==true) {
                            //将返回来的内容解码
                            String styleImgURL=jsonArray.getJSONObject(0).getString("StyleImgURL");
                            String imgResult=jsonArray.getJSONObject(0).getString("ImgResult");
                            //置值
                            String tmpServiceUrl=serviceUrl+"/PNG/"+styleImgURL;
                            //调用显示功能;
                            if (styleImgURL.equals("NULL")==false){
                                Log.d("GetWebData","图片路径获取成功:"+tmpServiceUrl);
                                //调用WebService过程并处理界面更新;
                                GetWebImage(tmpServiceUrl, styleImgURL, null);
                            }
                        }
                        //设定辅料工序;
                        if (jsonArray.getJSONObject(0).has("SetWorkProcType")==true){
                            if (jsonArray.getJSONObject(0).getString("SetWorkProcType").equals("OK")) {
                                String styleProID=jsonArray.getJSONObject(0).getString("StyleProID");
                                for (int i = 0; i < procList.length(); i++) {
                                    if (procList.getJSONObject(i).getString("StyleProID").equals(styleProID)){
                                        if (jsonArray.getJSONObject(0).getString("Type").equals("辅料")){
                                            procList.getJSONObject(i).put("BaseKey","true");
                                            //更新表;
                                            mainDB.execSQL("UPDATE ProcList SET BaseKey=? WHERE DepartNo=? and  OrderNo=? and StyleNo=? and StyleID=? and StyleProID=?",new String[]{"true",curDepartNo,curOrderNo,curStyleNo,curStyleID,styleProID});
                                        }
                                        if (jsonArray.getJSONObject(0).getString("Type").equals("大包")){
                                            procList.getJSONObject(i).put("BaseKey","false");
                                            //更新表;
                                            mainDB.execSQL("UPDATE ProcList SET BaseKey=? WHERE DepartNo=? and  OrderNo=? and StyleNo=? and StyleID=? and StyleProID=?",new String[]{"false",curDepartNo,curOrderNo,curStyleNo,curStyleID,styleProID});
                                        }
                                        //更新工序列表;
                                        ((BaseAdapter) procListView.getAdapter()).notifyDataSetChanged();
                                    }
                                }
                            } else {
                                curToast.setText(jsonArray.getJSONObject(0).getString("SetWorkProcType"));
                                curToast.show();
                            }

                        }
                    }
                    Log.d("msg","onPostExecute转换完成，准备显示。。。。。。。。");
                } catch (JSONException e) {
                    e.printStackTrace();
                    //关闭ProgressDialog
                    if (waitDialog.equals(null)==false) waitDialog.hide();
                    curToast.setText(e.getMessage());
                    curToast.show();
                }
            }
        }.execute(params);

    }

    public void GetWebImage(String serviceUrl, final String fileName, Map<String,Object> paramMap) {
        //组织参数传到匿名类中;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("serviceUrl",serviceUrl);
        params.put("fileName",fileName);
        params.put("paramMap",paramMap);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String,Object>,Void,Bitmap>()
        {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                waitDialog.show();
            }

            @Override
            protected Bitmap doInBackground(Map<String, Object>... params) {
                boolean ErrSign=false;
                String serviceUrl= (String) params[0].get("serviceUrl");
                Log.d("GetWebImage","图片接收A:---"+serviceUrl);
                String fileName= (String) params[0].get("fileName");
                Log.d("GetWebImage","图片接收B:---"+fileName);
                Bitmap bitmap = null;
                try {
                    //加载一个网络图片
                    InputStream is = new URL(serviceUrl).openStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    //保存图片;
                    saveBitmap(bitmap,fileName);
                    CurPhotoFileName =fileName;
                    return bitmap;
                } catch (HttpResponseException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (SoapFault soapFault) {
                    ErrSign=true;
                    soapFault.printStackTrace();
                } catch (IOException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (Exception e){
                    ErrSign=true;
                    e.printStackTrace();
                }
                //关闭ProgressDialog
                if (ErrSign==true) Log.d("msg","查询数据出错,错误异常抛出！");
                return null;
            }

            @Override
            protected void onPostExecute(Bitmap bm) {
                super.onPostExecute(bm);
                if (bm==null)
                {
                    if (waitDialog.equals(null)==false) waitDialog.hide();
                    return;
                }
                //这部分主要用于UI更新;
                Log.d("msg","图片接收成功。。。。。。。。");
                image_StylePic.setImageBitmap(bm);
                waitDialog.hide();
            }
        }.execute(params);

    }

    /**
     * @Title: getLoacalBitmap
     * @Description: 加载本地图片
     * @param @param url 本地路径
     * @param @return
     * @return Bitmap
     * @throws
     */
    public  Bitmap getLoacalBitmap(String url) {
        if (url != null) {
            FileInputStream fis=null;
            try {
                fis = new FileInputStream(url);
                return BitmapFactory.decodeStream(fis); // /把流转化为Bitmap图片
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return null;
            }finally{
                if(fis!=null){
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    fis=null;
                }
            }
        } else {
            return null;
        }
    }


    /** 保存文件 */
    public void saveBitmap(Bitmap bm,String fileName) {
        //String imgfilepath=activity.SaveFilePath+activity.SaveIMGFolder;
        String imgfilepath=getCacheDir().toString();
        Log.d("saveBitmap","imgfilepath:"+imgfilepath);
        File f = new File(imgfilepath, fileName);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
            Log.i("saveBitmap", "已经保存成功");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @Override
    public void onClick(View v) {
        hideBottomUIMenu();
        switch (v.getId())
        {
            case R.id.btn_departRefresh:
                //刷新员工;
                refreshEmpList(curDepartNo);
                break;
            case R.id.btn_ProcRefresh:
                //刷新工序;
                if (curStyleNo.length()==0)
                {
                    curToast.setText(getString(R.string.PlsSelectOrder));
                    curToast.show();
                    return;
                }
                if (edit_workDate.length()==0)
                {
                    curToast.setText(getString(R.string.PlsSelectArrangeDate));
                    curToast.show();
                    return;
                }
                NeedReLoad=true;
                refreshProcList(curDepartNo,curOrderNo,curStyleNo,curStyleID,curStyleSort,curWorkDate);
                break;
            case R.id.btn_AddEmpProc:
                if (selPlaceNo.length()==0)
                {
                    curToast.setText(getString(R.string.PlsSelectPlaceNo));
                    curToast.show();
                    return;
                }
                if (selEmpNo.length()==0)
                {
                    curToast.setText(getString(R.string.PlsSelectEmp));
                    curToast.show();
                    return;
                }
                //判断机台上是否有人;
                int placeIndex=Integer.parseInt(selPlaceNo)-1;
                try {
                    if ((arrMachineList.getJSONObject(placeIndex).getString("EmpNo").equals(selEmpNo)==false)
                            &&(arrMachineList.getJSONObject(placeIndex).getString("EmpNo").length()>0)){
                        AlertDialog alertDialog = new AlertDialog.Builder(this)
                                .setTitle(getString(R.string.SystemHint)).setMessage(getString(R.string.PlsLongPressPlaceDelInfo))
                                .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                }).create();

                        alertDialog.show(); // 显示对话框
                    }else
                    {
                        btn_AddEmpProc.setBackground(getResources().getDrawable(R.drawable.button_selector));
                        //增加工序到员工名下;
                        if (selEmpID.length()>0) AddEmpProc();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btn_ClrEmpProc:
                //清空员工名下的所有工序;
                if (selEmpID.length()>0) ClrEmpProc(curDepartNo,curOrderNo,curStyleNo,curStyleID,curStyleSort);
                break;
            case R.id.btn_ReArrangeProc:
                if (curStyleNo.length()==0)
                {
                    curToast.setText(getString(R.string.PlsQueryOrderHint));
                    curToast.show();
                    return;
                }
                AlertDialog alertDialog = new AlertDialog.Builder(v.getContext())
                        .setTitle(getString(R.string.SystemHint)).setMessage(getString(R.string.ClearArrangeWarnInfo))
                        .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                waitDialog.setMessage(getString(R.string.DeleteArrangeWaiting));
                                //清空所有员工安排;
                                ReEmpProc(curDepartNo,curOrderNo,curStyleNo,curStyleID,curStyleSort,curWorkDate);
                            }
                        }).setNegativeButton(getString(R.string.Cancel),
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        return;
                                    }
                                }).create(); // 创建对话框
                alertDialog.show(); // 显示对话框
                break;
            case R.id.btn_SaveProcScheme:
                btn_SaveProcScheme.setBackground(getResources().getDrawable(R.drawable.button_selector));
                if (curStyleNo.length()==0)
                {
                    curToast.setText(getString(R.string.PlsFilterOrderAndSelect));
                    curToast.show();
                    return;
                }
                //保存工序;
                SaveProcArrange(curDepartNo,curOrderNo,curStyleNo,curStyleID,curStyleSort,curWorkDate);
                break;
            case R.id.btn_ViewProcScheme:
                //刷新工序;
                if (curStyleNo.length()==0)
                {
                    curToast.setText(getString(R.string.PlsSelectOrder));
                    curToast.show();
                    return;
                }
                //显示安排情况;
                showArrangeActivity();
                break;
            case R.id.btn_CopyArrangeProc:
                //复制安排
                copySelectStyle();
                break;
            case R.id.btn_proc_switchPlace:
                //交换位置号;
                switchPlace();
                break;
            case R.id.btn_proc_autoPlace:
                //自动排车;
                NeedReLoad=true;
                autoPlace(curDepartNo,curOrderNo,curStyleNo,curStyleID,curStyleSort);
                break;
            case R.id.btn_LoginClose:
                this.finish();
                break;
            default:
                break;
        }
    }

    //交换位置号;
    private void switchPlace(){
        if (selPlaceNo.length()==0){
            curToast.setText(getString(R.string.PlsSelectReplace));
            curToast.show();
            return;
        }
        //判断机台上是否有人;
        int placeIndex=Integer.parseInt(selPlaceNo)-1;
        String tmpEmpNo="";
        String tmpEmpName="";
        try {
            tmpEmpNo=arrMachineList.getJSONObject(placeIndex).getString("EmpNo");
            tmpEmpName=arrMachineList.getJSONObject(placeIndex).getString("EmpName");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //创建布局
        LayoutInflater inflater=this.getLayoutInflater();
        final View text_input=inflater.inflate(R.layout.text_input_dialog, null);

        //Activity.findViewById最终还是会调用View.findViewById
        //因为在Activity的onCreate中一定会先setContentView的
        final EditText text_input_edit=(EditText)text_input.findViewById(R.id.text_input_edit);
        final TextView text_input_hint=(TextView)text_input.findViewById(R.id.text_input_hint);
        if (tmpEmpName.length()>0)
            text_input_hint.setText(getString(R.string.SelectPlace1)+selPlaceNo+getString(R.string.SelectPlace2)+tmpEmpName+getString(R.string.SelectPlace3));
        else
            text_input_hint.setText(getString(R.string.SelectPlace1)+selPlaceNo+getString(R.string.SelectPlace4));
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(android.R.drawable.ic_dialog_info).setView(text_input).setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //位置号
                        hideIM(text_input_edit);
                        if (text_input_edit.getText().length()>0)
                        {
                            if ((selPlaceNo.equals(text_input_edit.getText().toString())==false)
                                    &&(Integer.parseInt(text_input_edit.getText().toString())<=arrMachineList.length())
                                    &&(Integer.parseInt(text_input_edit.getText().toString())>0)) {
                                switchPlaceO2N(selPlaceNo, text_input_edit.getText().toString());
                            } else {
                                curToast.setText(getString(R.string.PlaceNoErrWarnHint));
                                curToast.show();
                            }

                        }else
                        {
                            curToast.setText(getString(R.string.NewPlaceErrHint));
                            curToast.show();
                        }
                    }
                }
        ).setNegativeButton(getString(R.string.Cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                hideIM(text_input);
            }
        }).setTitle(getString(R.string.PlaceReplaceHint));
        builder.show();
    }

    //将位置号对换;
    private void switchPlaceO2N(String oldplace,String newplace)
    {
        String OldEmpID="";
        String OldEmpNo="";
        String OldEmpName="";
        String OldWorkNames="";
        String OldMachineName="";
        String NewEmpID="";
        String NewEmpNo="";
        String NewEmpName="";
        String NewWorkNames="";
        String NewMachineName="";
        //判断机台上是否有人;
        int oldplaceIndex=Integer.parseInt(oldplace)-1;
        try {
            OldEmpID=arrMachineList.getJSONObject(oldplaceIndex).getString("EmpID");
            OldEmpNo=arrMachineList.getJSONObject(oldplaceIndex).getString("EmpNo");
            OldEmpName=arrMachineList.getJSONObject(oldplaceIndex).getString("EmpName");
            OldWorkNames=arrMachineList.getJSONObject(oldplaceIndex).getString("WorkNames");
            OldMachineName=arrMachineList.getJSONObject(oldplaceIndex).getString("MachineName");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        int newplaceIndex=Integer.parseInt(newplace)-1;
        try {
            NewEmpID=arrMachineList.getJSONObject(newplaceIndex).getString("EmpID");
            NewEmpNo=arrMachineList.getJSONObject(newplaceIndex).getString("EmpNo");
            NewEmpName=arrMachineList.getJSONObject(newplaceIndex).getString("EmpName");
            NewWorkNames=arrMachineList.getJSONObject(newplaceIndex).getString("WorkNames");
            NewMachineName=arrMachineList.getJSONObject(newplaceIndex).getString("MachineName");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //先执行员工位置互换;
        mainDB.execSQL("Update EmpProcList Set PlaceNo=? Where DepartNo=? AND EmpNo=? AND OrderNo=? AND StyleNo=? and PlaceNo=?",
                new String[]{newplace,curDepartNo,OldEmpNo,curOrderNo,curStyleNo,oldplace});
        mainDB.execSQL("Update EmpProcList Set PlaceNo=? Where DepartNo=? AND EmpNo=? AND OrderNo=? AND StyleNo=? and PlaceNo=?",
                new String[]{oldplace,curDepartNo,NewEmpNo,curOrderNo,curStyleNo,newplace});
        //清空原工序的员工安排;
        mainDB.execSQL("Update ProcList Set WorkArrEmps=?,WorkArrEmpNos=?,PlaceNos=? Where DepartNo=? and OrderNo=? and StyleNo=?",
                new String[]{"","","",curDepartNo,curOrderNo,curStyleNo});
        //重新组织安排;
        Cursor cur=mainDB.rawQuery("Select StyleProID,WorkLineNo,WorkNo,WorkName from ProcList Where DepartNo=? AND OrderNo=? AND StyleNo=?",
                new String[]{curDepartNo,curOrderNo,curStyleNo});
        while (cur.moveToNext())
        {
            String tmpStyleProID=cur.getString(cur.getColumnIndex("StyleProID"));
            String tmpWorkNo=cur.getString(cur.getColumnIndex("WorkNo"));
            String tmpWorkLineNo=cur.getString(cur.getColumnIndex("WorkLineNo"));
            String tmpEmpNos="";
            String tmpEmpNames="";
            String tmpPlaceNos="";
            System.out.println("cur:"+cur.getCount()+"--tmpWorkNo:"+tmpWorkNo+"   tmpStyleProID:"+tmpStyleProID);
            if (tmpWorkNo.length()>0) {
                Cursor curproc = mainDB.rawQuery("SELECT EmpList.EmpNo,EmpList.EmpName,EmpProcList.PlaceNo FROM EmpProcList inner join EmpList on EmpProcList.EmpNo=EmpList.EmpNo " +
                                "WHERE EmpProcList.DepartNo=? and EmpProcList.OrderNo=? and EmpProcList.StyleNo=? and EmpProcList.WorkNo=?",
                        new String[]{curDepartNo, curOrderNo, curStyleNo, tmpWorkNo});
                System.out.println("curproc:"+curproc.getCount());
                while (curproc.moveToNext())
                {
                    if (tmpEmpNames.length()>0)
                    {
                        tmpEmpNos=tmpEmpNos+","+curproc.getString(curproc.getColumnIndex("EmpNo"));
                        tmpEmpNames=tmpEmpNames+","+curproc.getString(curproc.getColumnIndex("EmpName"));
                        tmpPlaceNos=tmpPlaceNos+","+curproc.getString(curproc.getColumnIndex("PlaceNo"));
                    } else
                    {
                        tmpEmpNos=curproc.getString(curproc.getColumnIndex("EmpNo"));
                        tmpEmpNames=curproc.getString(curproc.getColumnIndex("EmpName"));
                        tmpPlaceNos=curproc.getString(curproc.getColumnIndex("PlaceNo"));
                    }
                }

            }
            System.out.println("tmpEmpNos:"+tmpEmpNos+"--tmpEmpNames:"+tmpEmpNames+"   tmpPlaceNos:"+tmpPlaceNos);
            //更新安排;
            if (tmpEmpNos.length()>0)
                mainDB.execSQL("Update ProcList Set WorkArrEmps=?,WorkArrEmpNos=?,PlaceNos=? Where DepartNo=? and OrderNo=? and StyleNo=? and WorkLineNo=? and WorkNo=?",
                        new String[]{tmpEmpNames,tmpEmpNos,tmpPlaceNos,curDepartNo,curOrderNo,curStyleNo,tmpWorkLineNo, tmpWorkNo});
        }
        cur.close();
        //刷新工序;
        cur = mainDB.rawQuery("SELECT * FROM ProcList WHERE DepartNo=? and  OrderNo=? and StyleNo=? ORDER BY ID",new String[]{curDepartNo,curOrderNo,curStyleNo});
        try {
            //初始化工序列表;
            procList=new JSONArray("[]");
            while (cur.moveToNext()) {
                JSONObject empJSON = new JSONObject();
                empJSON.put("ArrangeID",cur.getString(cur.getColumnIndex("ArrangeID")));
                empJSON.put("ArrangeDeID",cur.getString(cur.getColumnIndex("ArrangeDeID")));
                empJSON.put("SchemeID",cur.getString(cur.getColumnIndex("SchemeID")));
                empJSON.put("OrderNo", cur.getString(cur.getColumnIndex("OrderNo")));
                empJSON.put("StyleNo", cur.getString(cur.getColumnIndex("StyleNo")));
                empJSON.put("StyleID", cur.getString(cur.getColumnIndex("StyleID")));
                empJSON.put("StyleSort", cur.getString(cur.getColumnIndex("StyleSort")));
                empJSON.put("WorkDate", cur.getString(cur.getColumnIndex("WorkDate")));
                empJSON.put("StyleProID", cur.getString(cur.getColumnIndex("StyleProID")));
                empJSON.put("Part", cur.getString(cur.getColumnIndex("Part")));
                empJSON.put("PartIndex", cur.getString(cur.getColumnIndex("PartIndex")));
                empJSON.put("WorkLineNo", cur.getString(cur.getColumnIndex("WorkLineNo")));
                empJSON.put("WorkNo", cur.getString(cur.getColumnIndex("WorkNo")));
                empJSON.put("WorkName", cur.getString(cur.getColumnIndex("WorkName")));
                empJSON.put("MachineName", cur.getString(cur.getColumnIndex("MachineName")));
                empJSON.put("SlowTime", cur.getString(cur.getColumnIndex("SlowTime")));
                empJSON.put("WorkCT", cur.getString(cur.getColumnIndex("WorkCT")));
                empJSON.put("WorkArrEmps", cur.getString(cur.getColumnIndex("WorkArrEmps")));
                empJSON.put("WorkArrEmpNos", cur.getString(cur.getColumnIndex("WorkArrEmpNos")));
                empJSON.put("PlaceNos",cur.getString(cur.getColumnIndex("PlaceNos")));
                empJSON.put("BaseKey",cur.getString(cur.getColumnIndex("BaseKey")));
                empJSON.put("SelSign",(Boolean)false);
                procList.put(empJSON);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            curToast.setText(e.getMessage());
            curToast.show();
            Log.d("msg","创建empList----Json出错");
        }
        Log.d("msg","showProcList----记录条数为:"+cur.getCount());
        cur.close();
        //显示到工序中;
        final ProcGridAdapter procGridAdapter=new ProcGridAdapter(this);
        procListView.setAdapter(procGridAdapter);
        //更新排车图;
        try {
            //旧
            arrMachineList.optJSONObject(newplaceIndex).put("EmpID",OldEmpID);
            arrMachineList.optJSONObject(newplaceIndex).put("EmpNo",OldEmpNo);
            arrMachineList.optJSONObject(newplaceIndex).put("EmpName",OldEmpName);
            arrMachineList.optJSONObject(newplaceIndex).put("WorkNames",OldWorkNames);
            arrMachineList.optJSONObject(newplaceIndex).put("MachineName",OldMachineName);
            //新
            arrMachineList.optJSONObject(oldplaceIndex).put("EmpID",NewEmpID);
            arrMachineList.optJSONObject(oldplaceIndex).put("EmpNo",NewEmpNo);
            arrMachineList.optJSONObject(oldplaceIndex).put("EmpName",NewEmpName);
            arrMachineList.optJSONObject(oldplaceIndex).put("WorkNames",NewWorkNames);
            arrMachineList.optJSONObject(oldplaceIndex).put("MachineName",NewMachineName);
            //更新机台列表;
            ((BaseAdapter)arrMachineGrid.getAdapter()).notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    //自动排车;
    private void autoPlace(String departParam,String orderParam,String styleParam,String paramStyleID,String paramStyleSort)
    {
        NeedReLoad=false;
        waitDialog.setMessage(getString(R.string.RequestAutoArrangePlace));
        //执行SQL过程
        String methodName="ExecSql";
        //通过哈希数组来传递参数;
        Map<String,Object> paramMap=new HashMap<String,Object>();
        //可传递多个参数  paramMap.put(paramName, paramValue);
        paramMap.put("SqlComm", "Exec ScenePAD_AutoPlace @DepartmentNo='" + departParam + "',@OrderNo='"+orderParam+"',@StyleNo='"+styleParam+"',@StyleID='"+paramStyleID+"',@StyleSort='"+paramStyleSort+"'");
        System.out.println(paramMap);
        //调用WebService过程并处理界面更新;
        ReadProcSQLData(serviceUrl, methodName, paramMap);
    }
    //显示工序选择
    private void copySelectStyle(){
        selectStyleID="";
        selectOrderNo ="";
        selectStyleNo="";
        //创建布局
        LayoutInflater inflater=this.getLayoutInflater();
        final View proc_stylefind=inflater.inflate(R.layout.procslipt_stylefind, null);
        //Activity.findViewById最终还是会调用View.findViewById
        //因为在Activity的onCreate中一定会先setContentView的
        procOrderListGrid=(ListView)proc_stylefind.findViewById(R.id.procOrderListGrid);
        final Button btn_proc_style_find=(Button)proc_stylefind.findViewById(R.id.btn_proc_style_find);
        edit_orderNo=(EditText)proc_stylefind.findViewById(R.id.edit_orderNo);
        edit_styleNo=(EditText)proc_stylefind.findViewById(R.id.edit_styleNo);
        edit_orderNo.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                Log.d("edit_orderNo","setOnEditorActionListener---------------Start:"+actionId);
                Log.d("edit_orderNo","setOnEditorActionListener---------------KeyEvent:"+event);
                if (event!=null) {
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                        Log.d("edit_orderNo","setOnEditorActionListener---------------置焦点");
                        edit_styleNo.requestFocusFromTouch();//获取焦点 光标出现
                        edit_styleNo.requestFocus();
                    }
                }
                return false;
            }
        });
        edit_styleNo.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                Log.d("edit_styleNo","setOnEditorActionListener---------------Start:"+actionId);
                Log.d("edit_styleNo","setOnEditorActionListener---------------KeyEvent:"+event);
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        hideIM(v);
                        //执行刷新数据过程;
                        refreshOrderList(curDepartNo,edit_orderNo.getText().toString(),edit_styleNo.getText().toString(),curStyleSort);
                    }
                }
                return false;
            }
        });
        edit_styleNo.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 获得焦点
                    Log.d("edit_styleNo","setOnFocusChangeListener---------------Start");
                    showIM(v);
                    Log.d("edit_styleNo","setOnFocusChangeListener---------------Over");
                } else {
                    // 失去焦点
                    hideIM(v);
                }
            }
        });
        btn_proc_style_find.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideIM(v);
                //调用数据;
                refreshOrderList(curDepartNo,edit_orderNo.getText().toString(),edit_styleNo.getText().toString(),curStyleSort);
            }
        });
        procOrderListGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    selectStyleID= OrderJSONArray.getJSONObject(position).getString("StyleID");
                    selectOrderNo = OrderJSONArray.getJSONObject(position).getString("OrderNo");
                    selectStyleNo= OrderJSONArray.getJSONObject(position).getString("StyleNo");
                    selectStyleSort= OrderJSONArray.getJSONObject(position).getString("StyleSort");
                } catch (JSONException e) {
                    e.printStackTrace();
                    curToast.setText(e.getMessage());
                    curToast.show();
                }

            }
        });
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(proc_stylefind).setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        if (selectStyleID.length()>0) {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                                field.setAccessible(true );
                                field.set(dialog,true );
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                            catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            // 创建提示对话框
                            AlertDialog alertDialog = new AlertDialog.Builder(ProcsliptActivity.this)
                                    .setTitle(getString(R.string.SystemHint)).setMessage(getString(R.string.AreYouAffirm1)+selectStyleNo+"["+ selectOrderNo +"]"+getString(R.string.ProcCopyHint)+curStyleNo+"["+curOrderNo+"]？")
                                    .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            //执行Copy过程，OK后，调用重新下载;
                                            CopyStyleArrange(curDepartNo,curOrderNo,curStyleNo,curStyleSort,curStyleID, selectOrderNo,selectStyleNo,selectStyleID,selectStyleSort);
                                        }
                                    }).setNegativeButton(getString(R.string.Cancel),null).create();
                            alertDialog.show(); // 显示对话框
                        } else {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                                field.setAccessible(true );
                                field.set( dialog,false );
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                            catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            curToast.setText(getString(R.string.PlsFilterOrderAndSelect));
                            curToast.show();
                        }
                    }
                }
        ).setNegativeButton(getString(R.string.Cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Field field = null;
                try {
                    field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                    field.setAccessible(true );
                    field.set(dialog,true );
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                Log.v("tag","取消");
            }
        }).setTitle(getString(R.string.CopyProcArrange));
        //设定对话框大小
        AlertDialog altdialog=builder.show();
        altdialog.getWindow().setLayout(800, LinearLayout.LayoutParams.WRAP_CONTENT);
    }


    //工序表格适配器;
    public final class SelectOrderListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public SelectOrderListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return OrderJSONArray.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return OrderJSONArray.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.procslipt_styleitem, null, false);
            convertView.setBackground(getResources().getDrawable(R.drawable.orderlist_selector));
            int ct_max_background = getResources().getColor(R.color.ct_max_background);
            int ct_nor_background = getResources().getColor(R.color.ct_nor_background);
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                TextView tv = (TextView) convertView.findViewById(R.id.text_proc_startdate);// 显示文字
                tv.setText(OrderJSONArray.optJSONObject(position).get("StartDate").toString());
                tv = (TextView) convertView.findViewById(R.id.text_proc_orderno);// 显示文字
                tv.setText(OrderJSONArray.optJSONObject(position).get("OrderNo").toString());
                tv = (TextView) convertView.findViewById(R.id.text_proc_styleno);// 显示文字
                tv.setText(OrderJSONArray.optJSONObject(position).get("StyleNo").toString());
                tv = (TextView) convertView.findViewById(R.id.text_proc_stylesort);// 显示文字
                tv.setText(OrderJSONArray.optJSONObject(position).get("StyleSort").toString());
                tv = (TextView) convertView.findViewById(R.id.text_proc_number);// 显示文字
                tv.setText(OrderJSONArray.optJSONObject(position).get("Number").toString());
                tv = (TextView) convertView.findViewById(R.id.text_proc_samvalue);// 显示文字
                tv.setText(OrderJSONArray.optJSONObject(position).get("SAMValue").toString());
            } catch (JSONException e) {
                e.printStackTrace();
                curToast.setText(e.getMessage());
                curToast.show();
            }
            Log.d("msg","SelectOrderListAdapter_position:"+position);
            return convertView;
        }
    }

    //保存工序安排
    private void SaveProcArrange(String paramDepartNo, String paramOrderNo, String paramStyleNo,String paramStyleID,String paramStyleSort,String paramWorkDate) {
        //保存修改配置;
        SharedPreferences settings =this.getSharedPreferences(STORE_NAME, getApplication().MODE_PRIVATE);
        SharedPreferences.Editor set_editor=settings.edit();
        set_editor.putBoolean("NeedSubmit",false);
        set_editor.commit();
        Log.d("SaveProcArrange","SaveProcArrange-----------------------------------------Enter");
        waitDialog.setMessage(getString(R.string.UploadArrangeProcWait));
        //更新人数;
        mainDB.execSQL("Delete from EmpTotalCount");
        mainDB.execSQL("update ProcList Set PlanEmpNum=0 where DepartNo=? and OrderNo=? and StyleNo=?",new  String[]{paramDepartNo,paramOrderNo,paramStyleNo});
        mainDB.execSQL("INSERT OR REPLACE INTO EmpTotalCount(DepartNo,OrderNo,StyleNo,StyleProID,WorkNo,EmpCount) Select DepartNo,OrderNo,StyleNo,StyleProID,WorkNo,count(1) EmpCount From" +
                " EmpProcList  where length(empNo)>0 and DepartNo=? and OrderNo=? and StyleNo=? Group by DepartNo,OrderNo,StyleNo,StyleProID,WorkNo",new  String[]{paramDepartNo,paramOrderNo,paramStyleNo});
        mainDB.execSQL("Update ProcList Set PlanEmpNum=(select EmpCount from EmpTotalCount where ProcList.DepartNo=EmpTotalCount.DepartNo and ProcList.OrderNo=EmpTotalCount.OrderNo " +
                "and ProcList.StyleNo=EmpTotalCount.StyleNo and ProcList.WorkNo=EmpTotalCount.WorkNo)");
        JSONArray tmpArrangeList = null;
        //将数据读到JSONArray;
        try {
            tmpArrangeList=new JSONArray("[]");
            Cursor cur=mainDB.rawQuery("Select ArrangeDeID,StyleProID,WorkNo,WorkCT,WorkArrEmps,WorkArrEmpNos,PlaceNos,PlanEmpNum from ProcList where DepartNo=? and OrderNo=? and StyleNo=? and WorkCT>0 order by WorkLineNo",new String[]{paramDepartNo,paramOrderNo,paramStyleNo});
            if (cur.getCount()>0)
                while (cur.moveToNext()){
                    JSONObject empProcJSON = new JSONObject();
                    empProcJSON.put("ArrangeDeID",cur.getString(cur.getColumnIndex("ArrangeDeID")));
                    empProcJSON.put("StyleProID",cur.getString(cur.getColumnIndex("StyleProID")));
                    empProcJSON.put("WorkNo",cur.getString(cur.getColumnIndex("WorkNo")));
                    empProcJSON.put("WorkCT", cur.getString(cur.getColumnIndex("WorkCT")));
                    empProcJSON.put("WorkArrEmps", cur.getString(cur.getColumnIndex("WorkArrEmps")));
                    empProcJSON.put("WorkArrEmpNos", cur.getString(cur.getColumnIndex("WorkArrEmpNos")));
                    empProcJSON.put("PlaceNos", cur.getString(cur.getColumnIndex("PlaceNos")));
                    empProcJSON.put("PlanEmpNum", cur.getString(cur.getColumnIndex("PlanEmpNum")));
                    tmpArrangeList.put(empProcJSON);
                }
            cur.close();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //取CT，BudgetOut，BalanceRatio
        Cursor cur=mainDB.rawQuery("Select ArrangeID,CT,EmpCount,BudgetOut,BalanceRatio from ProcMaList where DepartNo=? and OrderNo=? and StyleNo=? ",new String[]{paramDepartNo,paramOrderNo,paramStyleNo});
        String tmpCT = "0";
        String tmpBudgetOut = "0";
        String tmpBalanceRatio = "0";
        String tmpArrangeID="";
        String tmpEmpCount="0";
        if (cur.getCount()>0) {
            cur.moveToFirst();
            tmpArrangeID= cur.getString(cur.getColumnIndex("ArrangeID"));
            tmpCT = String.valueOf(cur.getInt(cur.getColumnIndex("CT")));
            tmpEmpCount= String.valueOf(cur.getInt(cur.getColumnIndex("EmpCount")));
            tmpBudgetOut = String.valueOf(cur.getInt(cur.getColumnIndex("BudgetOut")));
            tmpBalanceRatio = String.valueOf(cur.getFloat(cur.getColumnIndex("BalanceRatio")));
        }
        cur.close();
        //调用WebService将数据保存至服务器;
        Log.d("SaveProcArrange","SaveProcArrange-----------------------------------------Upload");
        //执行WebService过程
        String methodName="TransProcArrange";
        //通过哈希数组来传递参数;
        Map<String,Object> paramMap=new HashMap<String,Object>();
        //可传递多个参数  paramMap.put(paramName, paramValue);
        paramMap.put("paramArrangeID",tmpArrangeID);
        paramMap.put("paramDepartNo", paramDepartNo);
        paramMap.put("paramOrderNo", paramOrderNo);
        paramMap.put("paramStyleNo", paramStyleNo);
        paramMap.put("paramStyleID",paramStyleID);
        paramMap.put("paramStyleSort",paramStyleSort);
        paramMap.put("paramWorkDate",paramWorkDate);
        paramMap.put("paramCT", tmpCT);
        paramMap.put("paramEmpCount", tmpEmpCount);
        paramMap.put("paramBudgetOut", tmpBudgetOut);
        paramMap.put("paramBalanceRatio", tmpBalanceRatio);
        paramMap.put("paramProcJSON", tmpArrangeList.toString());
        paramMap.put("paramUserNo", curLoginUserNo);
        //调用WebService过程并处理界面更新;
        GetWebData(serviceUrl, methodName, paramMap);
        System.out.println(paramMap);
        Log.d("SaveProcArrange","SaveProcArrange-----------------------------------------Over");
    }

    //增加工序到员工名下;
    private boolean AddEmpProc(){
        //修改保存配置;
        SharedPreferences settings = getSharedPreferences(STORE_NAME,getApplicationContext().MODE_PRIVATE);
        SharedPreferences.Editor set_editor=settings.edit();
        set_editor.putString("OrderNo",curOrderNo);
        set_editor.putString("StyleNo",curStyleNo);
        set_editor.putString("StyleID",curStyleID);
        set_editor.putString("StyleSort",curStyleSort);
        set_editor.putString("DepartNo",curDepartNo);
        set_editor.putString("Depart",curDepart);
        set_editor.putString("SAMValue",curSAMValue);
        set_editor.putInt("TT",curWorkTT);
        set_editor.putBoolean("NeedSubmit",true);
        set_editor.commit();
        if (selPlaceNo.equals(null)==true) {
            curToast.setText(getString(R.string.PlaceIsEmptyWarn));
            curToast.show();
        }
        //提醒需保存安排方案
        btn_SaveProcScheme.setBackground(getResources().getDrawable(R.drawable.button_hintselector));
        //将工序安排给员工;
        //将数据加载到empList中;
        try {
            boolean needInsert=true;
            for(int i=0;i<procList.length();i++) {
                Log.d("onClick","A-------------------");
                if (procList.getJSONObject(i).getBoolean("SelSign")==true) {
                    //取消选择状态;
                    procList.getJSONObject(i).put("SelSign",false);
                    String StyleProID=procList.getJSONObject(i).getString("StyleProID");
                    //默认需要增加安排;
                    needInsert = true;
                    for (int j = 0; j < empProcList.length(); j++) {
                        if (StyleProID.equals(empProcList.getJSONObject(j).getString("StyleProID"))==true)
                            needInsert = false;
                    }
                    if (needInsert==true)
                    {
                        //添加至工序列表;
                        String WorkArrEmps=procList.getJSONObject(i).getString("WorkArrEmps");
                        String WorkArrEmpNos=procList.getJSONObject(i).getString("WorkArrEmpNos");
                        String PlaceNos=procList.getJSONObject(i).getString("PlaceNos");
                        if (WorkArrEmps.length()>0) WorkArrEmps=WorkArrEmps+','+selEmpName;else WorkArrEmps=selEmpName;
                        if (WorkArrEmpNos.length()>0) WorkArrEmpNos=WorkArrEmpNos+','+selEmpNo;else WorkArrEmpNos=selEmpNo;
                        if (PlaceNos.length()>0) PlaceNos=PlaceNos+','+selPlaceNo;else PlaceNos=selPlaceNo;
                        procList.getJSONObject(i).put("WorkArrEmps",WorkArrEmps);
                        procList.getJSONObject(i).put("WorkArrEmpNos",WorkArrEmpNos);
                        procList.getJSONObject(i).put("PlaceNos",PlaceNos);
                        System.out.println("WorkArrEmps:"+WorkArrEmps+" WorkArrEmpNos:"+WorkArrEmpNos+" PlaceNos:"+WorkArrEmpNos+" StyleProID:"+StyleProID+" curDepartNo:"+curDepartNo+" curOrderNo:"+curOrderNo+" curStyleNo:"+curStyleNo+" curStyleID:"+curStyleID);
                        //更新相关字段;
                        mainDB.execSQL("UPDATE ProcList SET WorkArrEmps=?,WorkArrEmpNos=?,PlaceNos=? WHERE StyleProID=? and DepartNo=? and  OrderNo=? and StyleNo=? and StyleID=?",
                                new String[]{WorkArrEmps,WorkArrEmpNos,PlaceNos,StyleProID,curDepartNo,curOrderNo,curStyleNo,curStyleID});
                        //更新工序安排员工情况;
                        ((BaseAdapter) procListView.getAdapter()).notifyDataSetChanged();
                        //插入相关字段
                        mainDB.execSQL("INSERT INTO EmpProcList(DepartNo,EmpNo,OrderNo,StyleNo,StyleID,StyleSort,StyleProID,WorkLineNo,WorkNo,WorkName,MachineName,SlowTime,PlaceNo)" +
                                        " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",
                                new String[]{
                                        curDepartNo,selEmpNo,curOrderNo,curStyleNo,curStyleID,curStyleSort,StyleProID,
                                        procList.getJSONObject(i).getString("WorkLineNo"),
                                        procList.getJSONObject(i).getString("WorkNo"),
                                        procList.getJSONObject(i).getString("WorkName"),
                                        procList.getJSONObject(i).getString("MachineName"),
                                        procList.getJSONObject(i).getString("SlowTime"),selPlaceNo});
                        //更新到当前列表;
                        JSONObject empJSON = new JSONObject();
                        empJSON.put("SelSign",false);
                        empJSON.put("EmpNo",selEmpNo);
                        empJSON.put("StyleProID",StyleProID);
                        empJSON.put("WorkLineNo",procList.getJSONObject(i).getString("WorkLineNo"));
                        empJSON.put("WorkNo",procList.getJSONObject(i).getString("WorkNo"));
                        empJSON.put("WorkName",procList.getJSONObject(i).getString("WorkName"));
                        empJSON.put("MachineName", procList.getJSONObject(i).getString("MachineName"));
                        empJSON.put("SlowTime", procList.getJSONObject(i).getString("SlowTime"));
                        empJSON.put("PlaceNo", selPlaceNo);
                        empProcList.put(empJSON);
                        //更新到安排表;
                        int placeIndex=Integer.parseInt(selPlaceNo)-1;
                        arrMachineList.getJSONObject(placeIndex).put("EmpID",selEmpID);
                        arrMachineList.getJSONObject(placeIndex).put("EmpNo",selEmpNo);
                        arrMachineList.getJSONObject(placeIndex).put("EmpName",selEmpName);
                        arrMachineList.getJSONObject(placeIndex).put("MachineName",procList.getJSONObject(i).getString("MachineName"));
                        //显示当前位置员工对应工序;
                        String tmpWorkNames="";
                        Cursor cur=mainDB.rawQuery("Select WorkLineNo,WorkName from EmpProcList where DepartNo=? and EmpNo=? and OrderNo=? and StyleNo=? and StyleID=? and PlaceNo=?"
                                ,new String[]{curDepartNo,selEmpNo,curOrderNo,curStyleNo,curStyleID,selPlaceNo});
                        while (cur.moveToNext()) {
                            String tmpWorkNo=cur.getString(cur.getColumnIndex("WorkLineNo"));
                            String tmpWorkName=cur.getString(cur.getColumnIndex("WorkName"));
                            if (tmpWorkName.length()>14) tmpWorkName=tmpWorkName.substring(0,14)+"...";
                            if (tmpWorkNames.length()>0) {
                                tmpWorkNames = tmpWorkNames+"\r\n"+tmpWorkNo+"."+tmpWorkName;
                            } else tmpWorkNames = tmpWorkNo+"."+tmpWorkName;
                        }
                        arrMachineList.getJSONObject(placeIndex).put("WorkNames",tmpWorkNames);
                        String tmpPlaceNo=arrMachineList.getJSONObject(placeIndex).getString("PlaceNo");
                        String tmpMachineName=arrMachineList.getJSONObject(placeIndex).getString("MachineName");
                        mainDB.execSQL("Update ArrangeMachine Set EmpID=?,EmpNo=?,EmpName=?,MachineName=?,WorkNames=? where PlaceNo=?",new Object[]{selEmpID,selEmpNo,selEmpName,tmpMachineName,tmpWorkNames,tmpPlaceNo});
                    }
                }
            }
            //计算员工已安排的SAM值，并更新到对应列;
            int tmpSlowTime=0;
            for (int i=0;i<empProcList.length();i++) {
                tmpSlowTime=tmpSlowTime+empProcList.getJSONObject(i).getInt("SlowTime");
                //计算员工对应工序CT
                String StyleProID=empProcList.getJSONObject(i).getString("StyleProID");
                float TmpWorkCT=CalcProCT(curDepartNo,curOrderNo,curStyleNo,curStyleID,StyleProID,(int)empProcList.getJSONObject(i).getInt("SlowTime"));
                //保存工序CT
                Log.d("AddEmpProc",StyleProID);
                for (int j=0;j<procList.length();j++) {
                    if (StyleProID.equals(procList.getJSONObject(j).getString("StyleProID")))
                    {
                        Log.d("AddEmpProc"+String.valueOf(j),StyleProID+":"+procList.getJSONObject(j).getString("StyleProID"));
                        procList.getJSONObject(j).put("WorkCT", String.valueOf(Math.floor(TmpWorkCT*100)/100));
                        mainDB.execSQL("UPDATE ProcList SET WorkCT=? WHERE StyleProID=? and DepartNo=? and OrderNo=? and StyleNo=? and StyleID=?",
                                new Object[]{TmpWorkCT, StyleProID,curDepartNo,curOrderNo,curStyleNo,curStyleID});
                    }
                }
            }
            //更新工作人数，预计产量及平衡率;
            updateBudgetOut(curDepartNo,curOrderNo,curStyleNo,curStyleID);
            //更新员工SAM汇总
            mainDB.execSQL("UPDATE EmpList SET EmpCT=? WHERE EmpID=?",new Object[]{tmpSlowTime,selEmpID});
            for (int i=0;i<empList.length();i++) {
                if (selEmpID.equals(empList.getJSONObject(i).getString("EmpID"))) empList.getJSONObject(i).put("EmpCT",tmpSlowTime);
            }
            //检查按钮状态;
            checkEmpProcClrBtnState();
            //更新机台列表;
            ((BaseAdapter)arrMachineGrid.getAdapter()).notifyDataSetChanged();
            //更新工序列表;
            ((BaseAdapter) procListView.getAdapter()).notifyDataSetChanged();
            //更新员工工序安排情况;
            ((BaseAdapter)empProcGrid.getAdapter()).notifyDataSetChanged();
            //重新统计机台种类及数量;
            reTotalMachine();
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }
    }

    //计算当前工序CT;
    private float CalcProCT(String paramDepartNo,String paramOrderNo,String paramStyleNo,String paramStyleID,String paramProID,float NormalTime){
        float TmpValue=0;
        float TmpSlowTime=0;
        Cursor cur=mainDB.rawQuery("SELECT EmpNo,sum(SlowTime) SlowTime FROM EmpProcList where EmpNo IN (SELECT EmpNo from EmpProcList WHERE StyleProID=? and length(EmpNo)>0) and DepartNo=? and OrderNo=? and StyleNo=? and StyleID=?  GROUP BY EmpNo",
                new String[]{paramProID,paramDepartNo,paramOrderNo,paramStyleNo,paramStyleID});
        while (cur.moveToNext())
        {
            Log.d("MSG",cur.getString(cur.getColumnIndex("EmpNo"))+":"+cur.getInt(cur.getColumnIndex("SlowTime")));
            TmpSlowTime=cur.getInt(cur.getColumnIndex("SlowTime"));
            if(TmpSlowTime>0) TmpValue=TmpValue+NormalTime/TmpSlowTime;
        }
        cur.close();
        Log.d("CalcProCT:",String.valueOf(TmpValue));
        float TmpWorkCT=0;
        if (TmpValue>0) TmpWorkCT=(float)Math.floor(NormalTime/TmpValue*100)/100;
        return TmpWorkCT;
    }
    //更新当前合约的工作人数、预算产量、平衡率;
    private void updateBudgetOut(String paramDepartNo,String paramOrderNo,String paramStyleNo,String paramStyleID){
        int tmpMaxWorkCT=0;
        int tmpTotalSlowTime=0;
        int tmpEmpCount=0;
        int tmpBudgetOut=0;
        int tmpBalanceRatio=0;
        //获取最大的CT;
        Cursor curA=mainDB.rawQuery("SELECT Max(WorkCT) MaxWorkCT,Sum(SlowTime) TotalSlowTime FROM ProcList where DepartNo=? and OrderNo=? and StyleNo=? and StyleID=?",
                new String[]{paramDepartNo,paramOrderNo,paramStyleNo,paramStyleID});
        if (curA.getCount()>0)
        {
            curA.moveToFirst();
            tmpMaxWorkCT=curA.getInt(curA.getColumnIndex("MaxWorkCT"));
            tmpTotalSlowTime=curA.getInt(curA.getColumnIndex("TotalSlowTime"));
        }
        curA.close();
        //统计参与工作人数;
        Cursor curB=mainDB.rawQuery("SELECT EmpNo,count(1) EmpProcCount FROM EmpProcList where length(EmpNo)>0 and DepartNo=? and OrderNo=? and StyleNo=? and StyleID=? Group by EmpNo",
                new String[]{paramDepartNo,paramOrderNo,paramStyleNo,paramStyleID});
        tmpEmpCount=curB.getCount();
        curB.close();
        //计算产量及平衡率;
        tmpBudgetOut=0;
        tmpBalanceRatio=0;
        if (tmpMaxWorkCT>0)
        {
            tmpBudgetOut=curOperateTime*60/tmpMaxWorkCT;
            if (tmpEmpCount>0) tmpBalanceRatio=tmpTotalSlowTime/tmpEmpCount/tmpMaxWorkCT*100;
        }
        //更新到数据库中;
        mainDB.execSQL("Update ProcMaList set CT=?,EmpCount=?,BudgetOut=?,BalanceRatio=? where DepartNo=? and OrderNo=? and StyleNo=? and StyleID=?",new Object[]{tmpMaxWorkCT,tmpEmpCount,tmpBudgetOut,tmpBalanceRatio,paramDepartNo,paramOrderNo,paramStyleNo,paramStyleID});
        //更新到界面字段;
        text_ProcEmpCount.setText(String.valueOf(tmpEmpCount));
        text_ProcBudgetOut.setText(String.valueOf(tmpBudgetOut));
        text_ProcBalanceRatio.setText(String.valueOf(tmpBalanceRatio));
    }
    //清空员工名下工序;
    private boolean ClrEmpProc(String paramDepartNo,String paramOrderNo,String paramStyleNo,String paramStyleID,String paramStyleSort){
        //保存修改配置;
        SharedPreferences settings = getSharedPreferences(STORE_NAME, getApplicationContext().MODE_PRIVATE);
        SharedPreferences.Editor set_editor=settings.edit();
        set_editor.putString("OrderNo",curOrderNo);
        set_editor.putString("StyleNo",curStyleNo);
        set_editor.putString("StyleID",curStyleID);
        set_editor.putString("StyleSort",curStyleSort);
        set_editor.putString("DepartNo",curDepartNo);
        set_editor.putString("Depart",curDepart);
        set_editor.putString("SAMValue",curSAMValue);
        set_editor.putInt("TT",curWorkTT);
        set_editor.putBoolean("NeedSubmit",true);
        set_editor.commit();
        //提醒需保存安排方案
        btn_SaveProcScheme.setBackground(getResources().getDrawable(R.drawable.button_hintselector));
        //同步清除数据库内容;
        try {
            //遍列员工所有工序
            for (int i=0;i<empProcList.length();i++)
            {
                if (empProcList.getJSONObject(i).getBoolean("SelSign")==true) {
                    String StyleProID = empProcList.getJSONObject(i).getString("StyleProID");
                    Log.d("msg-Source", empProcList.getJSONObject(i).getString("WorkNo") + ":" + StyleProID);
                    for (int j = 0; j < procList.length(); j++) {
                        Log.d("msg-Target", procList.getJSONObject(j).getString("WorkNo") + ":" + procList.getJSONObject(j).getString("StyleProID"));
                        //如果工序相同，则需要从ProcList中减去
                        if ((StyleProID.equals(procList.getJSONObject(j).getString("StyleProID")) == true)
                                && (paramOrderNo.equals(procList.getJSONObject(j).getString("OrderNo")) == true)
                                && (paramStyleNo.equals(procList.getJSONObject(j).getString("StyleNo")) == true)
                                && (paramStyleID.equals(procList.getJSONObject(j).getString("StyleID")) == true)) {
                            String WorkArrEmps = procList.getJSONObject(j).getString("WorkArrEmps");
                            String WorkArrEmpNos = procList.getJSONObject(j).getString("WorkArrEmpNos");
                            String PlaceNos = procList.getJSONObject(j).getString("PlaceNos");
                            String arrPlaceNo="0";
                            String arrEmps[]=WorkArrEmps.split(",");
                            String arrEmpNos[]=WorkArrEmpNos.split(",");
                            String arrPlaceNos[]=PlaceNos.split(",");
                            for (int k=0;k<arrEmpNos.length;k++) {
                                System.out.println("-------------------selEmpNo:"+selEmpNo+"----"+arrEmpNos[k]+"-----------------");
                                if (arrEmpNos[k].equals(selEmpNo)) arrEmpNos[k]="";
                            }
                            //重新整理;
                            WorkArrEmps="";
                            WorkArrEmpNos="";
                            PlaceNos="";
                            for (int k=0;k<arrEmpNos.length;k++) {
                                if (arrEmpNos[k].length()>0){
                                    if (WorkArrEmps.length()>0) WorkArrEmps=WorkArrEmps+','+arrEmps[k]; else WorkArrEmps=arrEmps[k];
                                    if (WorkArrEmpNos.length()>0) WorkArrEmpNos=WorkArrEmpNos+','+arrEmpNos[k]; else WorkArrEmpNos=arrEmpNos[k];
                                    if (arrPlaceNos.length>k) arrPlaceNo=arrPlaceNos[k];else arrPlaceNo="0";
                                    if (PlaceNos.length()>0) PlaceNos=PlaceNos+','+arrPlaceNo; else PlaceNos=arrPlaceNo;
                                }
                            }
                            Log.d("msg", WorkArrEmpNos + ":" + WorkArrEmps+":"+PlaceNos);
                            //为界面刷新做准备;
                            procList.getJSONObject(j).put("WorkArrEmps", WorkArrEmps);
                            procList.getJSONObject(j).put("WorkArrEmpNos", WorkArrEmpNos);
                            procList.getJSONObject(j).put("PlaceNos", PlaceNos);


                            //更新相关字段;
                            mainDB.execSQL("UPDATE ProcList SET WorkArrEmps=?,WorkArrEmpNos=?,PlaceNos=? WHERE DepartNo=? and OrderNo=? and StyleNo=? and StyleID=? and StyleProID=?", new String[]{WorkArrEmps, WorkArrEmpNos,PlaceNos, paramDepartNo, paramOrderNo, paramStyleNo, paramStyleID, StyleProID});
                        }
                    }
                    //删除员工已安排工序;
                    mainDB.execSQL("DELETE FROM EmpProcList WHERE DepartNo=? and EmpNo=? and OrderNo=? and StyleNo=? and StyleID=? and StyleProID=?",new String[]{paramDepartNo,selEmpNo,paramOrderNo,paramStyleNo,paramStyleID,StyleProID});
                }
            }
            System.out.println("计算员工需移除工序CT;");
            //计算员工需移除工序CT;
            int tmpSlowTime=0;
            for (int i=0;i<empProcList.length();i++) {
                if (empProcList.getJSONObject(i).getBoolean("SelSign")==true) {
                    //计算员工对应工序CT
                    String StyleProID = empProcList.getJSONObject(i).getString("StyleProID");
                    float TmpWorkCT = CalcProCT(paramDepartNo, paramOrderNo, paramStyleNo, paramStyleID, StyleProID, (int) empProcList.getJSONObject(i).getInt("SlowTime"));
                    //保存工序CT
                    Log.d("AddEmpProc", StyleProID);
                    for (int j = 0; j < procList.length(); j++) {
                        if (StyleProID.equals(procList.getJSONObject(j).getString("StyleProID"))) {
                            Log.d("AddEmpProc" + String.valueOf(j), StyleProID + ":" + procList.getJSONObject(j).getString("StyleProID")+"--WorkCT:"+String.valueOf(Math.floor(TmpWorkCT * 100) / 100));
                            procList.getJSONObject(j).put("WorkCT", String.valueOf(Math.floor(TmpWorkCT * 100) / 100));
                            mainDB.execSQL("UPDATE ProcList SET WorkCT=? WHERE StyleProID=? and DepartNo=? and OrderNo=? and StyleNo=? and StyleID=?",
                                    new Object[]{TmpWorkCT, StyleProID, paramDepartNo, paramOrderNo, paramStyleNo, paramStyleID});
                        }
                    }
                } else tmpSlowTime = tmpSlowTime + empProcList.getJSONObject(i).getInt("SlowTime");
            }
            //重新获取员工工序列表;
            reGetEmpProcList(paramDepartNo,selEmpNo,paramOrderNo,paramStyleNo,paramStyleID,paramStyleSort);
            mainDB.execSQL("UPDATE EmpList SET EmpCT=? WHERE EmpID=?",new Object[]{tmpSlowTime,selEmpID});
            //更新CT
            for (int i=0;i<empList.length();i++) {
                if (selEmpID.equals(empList.getJSONObject(i).getString("EmpID"))==true) empList.getJSONObject(i).put("EmpCT",tmpSlowTime);
            }
            //检查按键状态;
            checkEmpProcClrBtnState();
            //更新工作人数，预计产量及平衡率;
            updateBudgetOut(paramDepartNo,paramOrderNo,paramStyleNo,paramStyleID);
            //更新机台列表;
            ((BaseAdapter)arrMachineGrid.getAdapter()).notifyDataSetChanged();
            //更新工序列表;
            ((BaseAdapter) procListView.getAdapter()).notifyDataSetChanged();
            //更新员工工序安排情况;
            showEmpProcList(paramDepartNo,selEmpNo,paramOrderNo,paramStyleNo,paramStyleID,paramStyleSort);
            //更新车位安排情况;
            showArrMachineGrid(paramDepartNo,paramOrderNo,paramStyleNo,paramStyleID,paramStyleSort);
            //重新统计机台种类及数量;
            reTotalMachine();
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

    //清空所有工序安排;
    private boolean ReEmpProc(String paramDepartNo,String paramOrderNo,String paramStyleNo,String paramStyleID,String paramStyleSort,String paramWorkDate) {
        mainDB.execSQL("UPDATE ProcList SET WorkArrEmps=?,WorkArrEmpNos=?,PlaceNos='',WorkCT=0 WHERE DepartNo=? AND OrderNo=? AND StyleNo=? AND StyleID=?",new String[]{"","",paramDepartNo,paramOrderNo,paramStyleNo,paramStyleID});
        mainDB.execSQL("UPDATE EmpList SET EmpCT=0");
        mainDB.execSQL("DELETE FROM EmpProcList where DepartNo=? AND OrderNo=? AND  StyleNo=? AND StyleID=?",new String[]{paramDepartNo,paramOrderNo,paramStyleNo,paramStyleID});
        mainDB.execSQL("UPDATE ArrangeMachine Set EmpID=?,EmpNO=?,EmpName=?,WorkNames=?,MachineName=?",new String[]{"","","","",""});
        //刷新数据;
        showProcList(paramDepartNo,paramOrderNo,paramStyleNo,paramStyleID,paramStyleSort,paramWorkDate);
        showEmpProcList(paramDepartNo,selEmpNo,paramOrderNo,paramStyleNo,paramStyleID,paramStyleSort);
        return false;
    }
    // /判断外部存储是否可读写
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //隐藏输入法;
        hideIM(view);
        if (parent==empListView) {
            if (selPlaceNo.equals(null)==true) {
                curToast.setText(getString(R.string.PlaceIsEmptyWarn));
                curToast.show();
            }
            view.setSelected(true);
            //置当前选中的员工;
            selEmpID=SourceEmpList.get(position).getEmpID();
            selEmpNo=SourceEmpList.get(position).getEmpNo();
            selEmpName=SourceEmpList.get(position).getEmpName();
            for (int i=0;i<SourceEmpList.size()-1;i++)
            {
                if (i!=position) SourceEmpList.get(i).setSelSign("");
                else SourceEmpList.get(i).setSelSign("★");
            }
            //更新显示;
            ((BaseAdapter)empListView.getAdapter()).notifyDataSetChanged();

            text_SelEmpName.setText(selEmpNo);
            if (selPlaceNo.length()>0) {
                int placeIndex = Integer.parseInt(selPlaceNo) - 1;
                try {
                    if (arrMachineList.getJSONObject(placeIndex).getString("WorkNames").length()>0)
                    {
                        selPlaceNo = "";
                        text_SelPlaceNo.setText(getString(R.string.PlsSelectPlaceNoShot));
                        text_SelPlaceNo.setBackgroundResource(R.drawable.place_nor_backgroup);
                    } else {
                        arrMachineList.getJSONObject(placeIndex).put("EmpID",selEmpID);
                        arrMachineList.getJSONObject(placeIndex).put("EmpNo",selEmpNo);
                        arrMachineList.getJSONObject(placeIndex).put("EmpName",selEmpName);
                        //更新机台列表;
                        ((BaseAdapter)arrMachineGrid.getAdapter()).notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else
            {
                selPlaceNo = "";
                text_SelPlaceNo.setText(getString(R.string.PlsSelectPlaceNo));
                text_SelPlaceNo.setBackgroundResource(R.drawable.place_nor_backgroup);
            }
            //显示员工已安排工序;
            showEmpProcList(curDepartNo,selEmpNo,curOrderNo,curStyleNo,curStyleID,curStyleSort);
            //消息提示;
            //Toast.makeText(getContext(), ((SortModel)empListAdapter.getItem(position)).getEmpName(), Toast.LENGTH_SHORT).show();
        }
        if (parent== procListView) {
            //置选择
            try {
                boolean curSelSign=procList.optJSONObject(position).getBoolean("SelSign");
                curSelSign=!curSelSign;
                procList.optJSONObject(position).put("SelSign",curSelSign);
                if (curSelSign==true) view.setBackgroundResource(R.drawable.procitem_sel_background); else {
                    if (procList.optJSONObject(position).get("WorkArrEmps").toString().length()>0)
                    {
                        if (procList.optJSONObject(position).getInt("WorkCT")> curWorkTT)
                            view.setBackgroundResource(R.drawable.procitem_err_background);
                        else view.setBackgroundResource(R.drawable.procitem_arg_background);
                    } else view.setBackgroundResource(R.drawable.procitem_background);
                }
                //如果员工已被选择
                //提醒需增加己选工序;
                if ((selEmpNo.length()>0)&&(selPlaceNo.length()>0)) btn_AddEmpProc.setBackgroundResource(R.drawable.button_hintselector);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (parent==empProcGrid) {
            //置选择
            try {
                boolean curSelSign=empProcList.optJSONObject(position).getBoolean("SelSign");
                curSelSign=!curSelSign;
                empProcList.optJSONObject(position).put("SelSign",curSelSign);
                if (curSelSign==true) view.setBackgroundResource(R.drawable.procitem_sel_background);
                else {
                    view.setBackgroundResource(R.drawable.procitem_background);
                }
                //检查是否选择了工序，如果选择了则提醒按钮;
                checkEmpProcClrBtnState();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (parent== arrMachineGrid) {
            try {
                selPlaceNo=String.valueOf(arrMachineList.optJSONObject(position).getInt("PlaceNo"));
                text_SelPlaceNo.setText(getString(R.string.NO)+" "+selPlaceNo+" "+getString(R.string.NO1));
                text_SelPlaceNo.setBackgroundResource(R.drawable.place_sel_backgroup);
                //根据位置上对应的员工显示;
                //置当前选中的员工;
                String tmpselEmpID=arrMachineList.optJSONObject(position).getString("EmpID");
                String tmpselWorkNames=arrMachineList.optJSONObject(position).getString("WorkNames");
                if (tmpselEmpID.length()>0) {
                    selEmpID = arrMachineList.optJSONObject(position).getString("EmpID");
                    selEmpNo = arrMachineList.optJSONObject(position).getString("EmpNo");
                    selEmpName = arrMachineList.optJSONObject(position).getString("EmpName");
                    text_SelEmpName.setText(selEmpNo);
                    //显示员工已安排工序;
                    showEmpProcList(curDepartNo, selEmpNo, curOrderNo, curStyleNo, curStyleID,curStyleSort);
                    //遍列位置对应的工序并选中;
                    for (int i=0;i<empProcList.length();i++) {
                        String selWorkNo=empProcList.getJSONObject(i).getString("WorkNo");
                        Cursor cur=mainDB.rawQuery("Select WorkName from EmpProcList Where DepartNo=? AND EmpNo=? AND OrderNo=? AND StyleNo=? AND StyleID=? and WorkNo=? and PlaceNo=? ",
                                new String[]{curDepartNo,selEmpNo,curOrderNo,curStyleNo,curStyleID,selWorkNo,selPlaceNo});
                        if (cur.getCount()>0) empProcList.optJSONObject(i).put("SelSign", true);
                        else empProcList.optJSONObject(i).put("SelSign", false);
                    }
                    //更新显示;
                    ((BaseAdapter)empProcGrid.getAdapter()).notifyDataSetChanged();
                    //判断是否需要显示删除按钮;
                    checkEmpProcClrBtnState();
                } /*else
                {
                    if ((selEmpNo.length()>0)&&(tmpselEmpID.length()==0)) {
                        arrMachineList.getJSONObject(position).put("EmpID", selEmpID);
                        arrMachineList.getJSONObject(position).put("EmpNo", selEmpNo);
                        arrMachineList.getJSONObject(position).put("EmpName", selEmpName);
                        //更新机台列表;
                        ((BaseAdapter) arrMachineGrid.getAdapter()).notifyDataSetChanged();
                    }
                }*/
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    //检查员工工序移除状态;
    private void checkEmpProcClrBtnState(){
        try {
            int selEmpProcCount=0;
            for (int i=0;i<empProcList.length();i++)
            {
                if (empProcList.optJSONObject(i).getBoolean("SelSign")==true) selEmpProcCount++;
            }
            if (selEmpProcCount>0) {
                btn_ClrEmpProc.setEnabled(true);
                btn_ClrEmpProc.setBackgroundResource(R.drawable.button_hintselector);
            } else {
                btn_ClrEmpProc.setBackgroundResource(R.drawable.buttonbackground);
                btn_ClrEmpProc.setEnabled(false);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public final class ProcGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public ProcGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return procList.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return procList.get(position);
            } catch (JSONException e) {
                System.out.println("getItem取JSON数据出错!");
                e.printStackTrace();
                return  null;
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.procgrid_item, null, false);
            int ct_max_background = getResources().getColor(R.color.ct_max_background);
            int ct_nor_background = getResources().getColor(R.color.ct_nor_background);
            try {
                boolean curSelSign=procList.optJSONObject(position).getBoolean("SelSign");
                if (curSelSign==true) convertView.setBackgroundResource(R.drawable.procitem_sel_background); else {
                    if (procList.optJSONObject(position).get("WorkArrEmps").toString().length()>0)
                    {
                        if (procList.optJSONObject(position).getInt("WorkCT")> curWorkTT)
                            convertView.setBackgroundResource(R.drawable.procitem_err_background);
                        else convertView.setBackgroundResource(R.drawable.procitem_arg_background);
                    } else convertView.setBackgroundResource(R.drawable.procitem_background);
                }
                TextView tv = (TextView) convertView.findViewById(R.id.procGrid_workNoText);// 显示文字
                tv.setText(procList.optJSONObject(position).get("WorkLineNo").toString());
                tv = (TextView) convertView.findViewById(R.id.procGrid_workNameText);// 显示文字
                tv.setText(procList.optJSONObject(position).get("WorkName").toString());
                tv = (TextView) convertView.findViewById(R.id.procGrid_MachineNameText);// 显示文字
                tv.setText(procList.optJSONObject(position).get("MachineName").toString());
                tv = (TextView) convertView.findViewById(R.id.procGrid_SlowTimeText);// 显示文字
                tv.setText(procList.optJSONObject(position).get("SlowTime").toString());
                tv = (TextView) convertView.findViewById(R.id.procGrid_CTText);// 显示文字
                tv.setText(procList.optJSONObject(position).getString("WorkCT"));
                tv = (TextView) convertView.findViewById(R.id.procGrid_PartText);// 显示文字
                tv.setText(procList.optJSONObject(position).get("Part").toString());
                if (procList.getJSONObject(position).getString("BaseKey").equals("true")){
                    tv.setTextColor(getResources().getColor(R.color.orchid));
                } else tv.setTextColor(getResources().getColor(R.color.ProcItemParttext));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.d("msg","EmpGridAdapter_position:"+position);
            return convertView;
        }
    }


    public final class EmpProcGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public EmpProcGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return empProcList.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return empProcList.get(position);
            } catch (JSONException e) {
                System.out.println("getItem取JSON数据出错!");
                e.printStackTrace();
                return  null;
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.empprocgrid_item, null, false);
            try {
                boolean curSelSign=empProcList.optJSONObject(position).getBoolean("SelSign");
                if (curSelSign==true) convertView.setBackgroundResource(R.drawable.procitem_sel_background);
                else convertView.setBackgroundResource(R.drawable.procitem_background);
                TextView tv = (TextView) convertView.findViewById(R.id.empprocGrid_workNoText);// 显示文字
                tv.setText(empProcList.optJSONObject(position).get("WorkLineNo").toString());
                tv = (TextView) convertView.findViewById(R.id.empprocGrid_workNameText);// 显示文字
                tv.setText(empProcList.optJSONObject(position).get("WorkName").toString());
                tv = (TextView) convertView.findViewById(R.id.empprocGrid_SlowTimeText);// 显示文字
                tv.setText(empProcList.optJSONObject(position).get("SlowTime").toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.d("msg","EmpGridAdapter_position:"+position);
            return convertView;
        }
    }


    /**
     * 复制单个文件
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    public void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ( (byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        }
        catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }

    }

    /**
     * 复制整个文件夹内容
     * @param oldPath String 原文件路径 如：c:/fqf
     * @param newPath String 复制后路径 如：f:/fqf/ff
     * @return boolean
     */
    public void copyFolder(String oldPath, String newPath) {

        try {
            (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
            File a=new File(oldPath);
            String[] file=a.list();
            File temp=null;
            for (int i = 0; i < file.length; i++) {
                if(oldPath.endsWith(File.separator)){
                    temp=new File(oldPath+file[i]);
                }
                else{
                    temp=new File(oldPath+File.separator+file[i]);
                }

                if(temp.isFile()){
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" +
                            (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ( (len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if(temp.isDirectory()){//如果是子文件夹
                    copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
                }
            }
        }
        catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();

        }

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (waitDialog!=null) waitDialog.dismiss();
    }
}
